需要插件
工程结构
launch.json
{
"version": "0.2.0",
"configurations": [
{
"name": "C/C++: g++ build and debug active file",
"type": "cppdbg",
"request": "launch",
"program": "${command:cmake.launchTargetPath}",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"miDebuggerPath": "/usr/bin/gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
}
]
}
program": "${command:cmake.launchTargetPath} :是执行CMake Tools插件里面的命令。将目标可执行文件的路径告诉VSCode。
main.cpp
#include <stdio.h>
int main(int argc, char *argv[]) {
printf("hello world\n");
return 0;
}
CMakeLists.txt
CMAKE_MINIMUM_REQUIRED(VERSION 3.10)
PROJECT(demo)
aux_source_directory(./src DIR_SRC)
add_executable(demo ${
DIR_SRC})
编译调试
按下 F5,就会触发cmake编译构建。构建生成的中间文件会放在build目录下,里面有几个重要文件。
- compile_commands.json:编译数据库,clangd插件会分析这个文件,生成代码索引。这样后面我们写代码就有代码提示,代码自动补全
- demo:make之后生成的可执行文件
要让clangd生成index文件,我们需要重启下VSCode。每次启动VSCode,clangd都会建立一遍索引,如果代码量庞大,这个过程会需要一定的时间,索引文件会放在.cache目录下。
可以通过du命令,查看.cache目录大小:
lorien@ubuntu20:/work2/cmake/cpp$ du -h .cache/
8.0K .cache/clangd/index
12K .cache/clangd
16K .cache/