所需要插件:
c/c++
c++intellisense
cmark
cmarktools
文件结构分为五部分,.vscode文件夹存放配置文件。build文件夹存放中间生成的静态库、临时文件、可执行文件等,可直接删除,避免了对源程序的污染。src文件存放cpp源程序。最后为主程序main.cpp以及对应的cmakelists.txt文件。
程序将cpp源程序和main.cpp分开存放,事实上,可直接合并到src文件夹中.这样只写一个cmakelists.txt文件即可。
默认生成(ctrl+shift+p 输入configurations),可不用修改
{
"configurations": [
{
"name": "Win32",
"includePath": [
"${workspaceFolder}/**"
],
"defines": [
"_DEBUG",
"UNICODE",
"_UNICODE"
],
"compilerPath": "C:\\Program Files\\mingw64\\bin\\gcc.exe",
"cStandard": "c11",
"cppStandard": "c++17",
"intelliSenseMode": "clang-x64",
"configurationProvider": "ms-vscode.cmake-tools"
}
],
"version": 4
}
可直接复制使用,需要注意两点:
"miDebuggerPath"
一定是自己当前使用电脑的gdb.exe路径"program"
一定是cmakelists.txt生成的可执行文件的路径及名字"preLaunchTask"
如果要只调试当前生成的exe文件,可将此行注释。如果是先build再直接调试则不用注释。(注:build 和debug是分开的,不注释则合并在一起操作了,如果注释了,要先手动build,再debug){
"version": "0.2.0",
"configurations": [
{
"name": "debug",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceRoot}\\build\\main.exe",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": true,
"MIMode": "gdb",
"miDebuggerPath": "C:\\Program Files\\mingw64\\bin\\gdb.exe",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"preLaunchTask": "make"
}
]
}
该配置文件下面有三个task
,供launch.json
文件中"preLaunchTask"
选择,选择make即可。
{
// 有关 tasks.json 格式的文档,请参见
// https://go.microsoft.com/fwlink/?LinkId=733558
"version": "2.0.0",
"tasks": [
{
"label": "cmake",
"options": {
"cwd": "${workspaceFolder}/build"
},
"type": "shell",
"command": "cmake -G 'Unix Makefiles' -DCMAKE_BUILD_TYPE=Debug .. ",
},
{
"label": "make",
"options": {
"cwd": "${workspaceFolder}/build"
},
"type": "shell",
"command": "mingw32-make -j8",
// "showOutput":"always",
"dependsOn": [
"cmake"
],
},
{
"label": "build",
"type": "shell",
"command": "${workspaceRoot}/build/build.sh",
"group": {
"kind": "build",
"isDefault": true
}
}
]
}
主程序目录下CMakeLists.txt
# CMake 最低版本号要求
cmake_minimum_required(VERSION 3.0.0)
# 项目名称
project(main)
#向工程添加多个特定的头文件搜索路径,路径之间用空格分隔
include_directories(include)
#添加 src 子目录
add_subdirectory(src)
# 指定生成目标 将名为 main.cpp 的源文件编译成一个名称为 ${PROJECT_NAME} 的可执行文件,即exe文件。
add_executable(${PROJECT_NAME} main.cpp)
#指定生成可执行文件的目录 PROJECT_BINARY_DIR 运行cmake命令的目录,通常是${PROJECT_SOURCE_DIR}/build
#SET(EXECUTABLE_OUTPUT_PATH ${PROJECT_BINARY_DIR}/bin)
# 添加链接库 可执行文件 ${PROJECT_NAME} 需要连接一个名为 Lib 的链接库
target_link_libraries(${PROJECT_NAME} LIB_SRCS)
子程序src文件下CMakeLists.txt
# 查找当前目录下的所有源文件
# 并将名称保存到 DIR_LIB_SRCS 变量
aux_source_directory(. DIR_LIB_SRCS)
# 生成链接库
add_library (LIB_SRCS ${DIR_LIB_SRCS})