打开一个含有CMakeLists.txt的文件夹
在.vscode要建立三个json文件才能对Cmake工程进行编译和调试,分别是c_cpp_properties.json,launch.json和tasks.json
- c_cpp_properties.json文件
Ctrl+Shift+P,输入C/C++,选择C/C++: Edit Configurations(JSON)
修改为如下:
{
"configurations": [
{
"name": "Linux",
"includePath": [
"${workspaceFolder}/**"
],
"defines": [],
"compilerPath": "/usr/bin/gcc",
"cStandard": "c11",
"cppStandard": "c++17",
"intelliSenseMode": "gcc-x64"
}
],
"version": 4
}
- launch.json文件
choose Run > Add Configuration... and then choose C++ (GDB/LLDB).
配置如下:
{
"version": "0.2.0",
"configurations": [
{
"name": "(gdb) Launch",
"type": "cppdbg",
"request": "launch",
// Resolved by CMake Tools:
"program": "${workspaceFolder}/build/Hello",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": true,
"MIMode": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
]
}
]
}
- tasks.json是编译任务的文件,
choose Terminal > Configure Default Build Task. A dropdown appears showing various predefined build tasks for C++ compilers. Choose C/C++: g++ build active file.
更改为如下:
{
"version": "2.0.0",
"tasks": [
{
"label": "make build",//编译的项目名,build
"type": "shell",
"command": "cd ./build ;cmake .. ;make",//编译命令
"group": {
"kind": "build",
"isDefault": true
}
},
{
"label": "clean",
"type": "shell",
"command": "make clean",
}
]
}
- 自己的CMakeLists.txt
cmake_minimum_required(VERSION 3.0)
project(Hello)
set(CMAKE_BUILD_TYPE "Debug")
add_definitions(-std=c++11)
set(SOURCE hello.cpp)
add_executable(${PROJECT_NAME} ${SOURCE})
- hello.cpp
#include
using namespace std;
int main()
{
cout << "hello world" << endl;
}
- ctrl+shift+B运行代码,成功。
可能存在的问题:
- 在刚开始打开vscode的时候,可能会自动建立build文件夹,在配置完3个文件后,把自动创建的build文件夹删除,然后再创建一个空的build文件夹,然后执行ctrl+shift+B
- launch.json文件创造出错,解决办法,删掉.vscode文件夹,然后关闭vscode ,重新打开,让c / c ++扩展来创建c_cpp_properties.json文件,然后再按Run > Add Configuration即可创建