Rate This Document
Findability
Accuracy
Completeness
Readability

Generating a JSON File

The compile_commands.json file is a JSON file that specifies the mapping between compiler command line options and source files. It is used by many code editors and tools for code completion, syntax check, and code navigation.

Procedure

The method of generating the compile_commands.json file depends on the compiler and build system you use. The following are some commonly used methods:

  • For a project built using CMake, you can add -DCMAKE_EXPORT_COMPILE_COMMANDS=ON to the CMake command to generate the compile_commands.json file. If the project depends on a third-party library, run the export command to import the environment variable of the third-party library.

    Example:

    1
    2
    export FFTW_INCLUDE=/path/to/FFTW/include
    cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=ON .
    

    /path/to/: path for storing the third-party library.

  • For a project built using Makefile, you can use either of the following methods to generate the file:
    • Method 1:
      1
      2
      3
      4
      5
      make --always-make --dry-run \
      | grep -wE 'gcc|g\+\+|c\+\+' \
      | grep -w '\-c' | sed 's|cd.*.\&\&||g' \
      | jq -nR '[inputs|{directory:".", command:., file:match(" [^ ]+$").string[1:]}]' \
      > compile_commands.json
      

      Before running the preceding commands, install the jq software. This section provides only common operations. For more information, see jq Manual.

    • Method 2:
      1
      compiledb -n make -f /path/to/Makefile
      

      Before running the preceding commands, install the compiledb software. This section provides only common operations. For more information, see compiledb.