When working with C or C++ projects, external tools like clangd, Clang-Tidy, and various IDE features rely on accurate knowledge of how each file in the project is compiled. This is where the Compilation Database comes in. Compilation Database is a JSON file (typically named compile_commands.json
) that lists all the compile commands used to build each source file in the project. It includes important details such as compiler options, include paths, and source file locations - everything the compiler needs to reproduce the build for each translation unit. This tutorial explains how to generate JSON compilation database using CMake.
Here's a minimal example CMakeLists.txt
that enables generation of the compile_commands.json
file:
cmake_minimum_required(VERSION 3.27)
project(myapp)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
add_executable(${PROJECT_NAME} main.cpp)
The CMAKE_EXPORT_COMPILE_COMMANDS
option tells CMake to generate the compile_commands.json
file during configuration.
Run the following command to configure the project and generate the compilation database:
cmake -S . -B build -DCMAKE_BUILD_TYPE=Release
After running this, you'll find a compile_commands.json
file inside the build
directory.
Here's a sample entry from a generated compile_commands.json
:
[
{
"directory": "/home/ubuntu/myproject/build",
"command": "/usr/bin/c++ -O3 -DNDEBUG -o CMakeFiles/myapp.dir/main.cpp.o -c /home/ubuntu/myproject/main.cpp",
"file": "/home/ubuntu/myproject/main.cpp",
"output": "CMakeFiles/myapp.dir/main.cpp.o"
}
]
This entry describes how the file main.cpp
is compiled, including the compiler, options, source path, and output path.
Leave a Comment
Cancel reply