打開一個含有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}/**",
"/usr/include/",
"/usr/local/include/",
"/usr/include/eigen3/"
],
"defines": [],
"compilerPath": "/usr/bin/gcc",
"cStandard": "c11",
"cppStandard": "c++17",
"intelliSenseMode": "linux-gcc-x64"
"configurationProvider": "ms-vscode.cmake-tools"
}
],
"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 <iostream>
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即可創建