创建一个vscode文件
记得一定要创建一个build文件夹,因为cmake编译过程中产生的中间文件会放到build文件夹中。
打开VScode
配置文件
launch.json
{
"version": "0.2.0",
"configurations": [
{
"name": "(gdb) Launch",
"type": "cppdbg",
"request": "launch",
// Resolved by CMake Tools:
"program": "${workspaceFolder}/${fileBasenameNoExtension}.out",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": true,
"MIMode": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
]
}
]
}
c_cpp_properties.json
点击右下角的Linux,随后点击编辑配置(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": "linux-gcc-x64",
"configurationProvider": "ms-vscode.cmake-tools"
}
],
"version": 4
}
task.json
点击终端----配置任务,选择第一个
{
"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",
}
]
}
配置CMAKE文件
在主目录下创建一个CMakeLists.txt
cmake_minimum_required(VERSION 3.16)
project(hello)
SET(EXECUTABLE_OUTPUT_PATH ./bin)
set(CMAKE_CXX_STANDARD 11)
find_package(OpenCV REQUIRED)
ADD_EXECUTABLE(hello src/test.cpp)
target_link_libraries(${PROJECT_NAME} ${OpenCV_LIBS})
这里笔者调用了OPENCV库,如果读者没有安装的话,可以将下面两行注释掉:
find_package(OpenCV REQUIRED)
target_link_libraries(${PROJECT_NAME} ${OpenCV_LIBS})
终端中运行程序
编写cpp文件,Shift+Ctrl+B编译,此时在build/bin中生成一个可执行文件,在终端中运行