本文参考:vscode一键配置C/C++多个C及CPP文件编译与tasks.json和launch.json原理 上一篇文章我们了解了VScode的工作原理,但是实际项目肯定是由多个源文件和模块组成。此时可以通过CMake进行配置工程,然后进行make编译。
上一篇文章我们知道VScode的工作原理主要依赖执行任务,即task.json 。通过CMake配置的工程我们只需要执行如下指令,即可完成整个项目的编译工作。
CMake . && make
实现思路
- 编写CMake脚本
- 运行CMake脚本生成makefile,然后执行make编译文件。
CMake输出目录依旧为:build 。所以任务主要分为两步:第一步创建Build 目录,第二步在Build目录执行CMake指令:CMake ../ 创建build目录
{
"type":"shell",
"label": "mkBuild",
"command":"mkdir",
"args": [
"-p",
"build"
],
"options": {
"cwd": "${workspaceFolder}"
},
},
在build目录执行CMake
{
"type":"shell",
"label": "executeCmake",
"command":"cmake",
"args": [
"../",
],
"options": {
"cwd": "${workspaceFolder}/build"
},
"dependsOn":"mkBuild"
},
在build目录执行make
{
"type":"shell",
"label": "execMake",
"command":"make",
"args": [
],
"options": {
"cwd": "${workspaceFolder}/build"
},
"dependsOn":"executeCmake"
}
此时在launch.json 里面指定任务execMake 即可。
"preLaunchTask": "execMake",
配置完成之后按运行F5调试即可,如果需要调试CMake一定需要指定set(CMAKE_BUILD_TYPE "Debug") ,否则将不可调试。 下面是完整的配置文件: task.json
{
"tasks": [
{
"type":"shell",
"label": "mkBuild",
"command":"mkdir",
"args": [
"-p",
"build"
],
"options": {
"cwd": "${workspaceFolder}"
},
},
{
"type":"shell",
"label": "executeCmake",
"command":"cmake",
"args": [
"../",
],
"options": {
"cwd": "${workspaceFolder}/build"
},
"dependsOn":"mkBuild"
},
{
"type":"shell",
"label": "execMake",
"command":"make",
"args": [
],
"options": {
"cwd": "${workspaceFolder}/build"
},
"dependsOn":"executeCmake"
}
],
"version": "2.0.0"
}
launch.json
{
"version": "0.2.0",
"configurations": [
{
"name": "g++ - 生成和调试活动文件",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}/build/hellow",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}/build",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"setupCommands": [
{
"description": "为 gdb 启用整齐打印",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"preLaunchTask": "execMake",
"miDebuggerPath": "/usr/bin/gdb"
}
]
}
由于CMakeLists.txt 的代码不具有通用性,所以这里暂时不贴出。如果不懂CMake的可以参考:一文读懂CMake
|