1. 创建项目工程及代码编写(Windows平台)
首先创建项目文件(文件名hello),并用VScode打开,进行项目编程。项目结构如下:
“避坑说明:头文件名称不要设置为include,会识别不到,报错”
对应文件代码如下:
头文件 print.h
#ifndef _PRINT_H_
#define _PRINT_H_
#include <iostream>
using namespace std;
void print();
#endif
源文件 print.cpp
#include "print.h"
void print()
{
cout << "hello world!" << endl;
}
源文件 main.cpp
#include <iostream>
#include "print.h"
using namespace std;
int main()
{
print();
return 0;
}
CMakeLists.txt文件
#规定cmake的最低版本要求
cmake_minimum_required (VERSION 3.10)
#设置c++编译器
set(CMAKE_CXX_COMPILER "g++")
#项目的名称,可以和文件夹名称(HELLO)不同
project(Cmake_print)
#添加头文件的搜索路径
include_directories(${PROJECT_SOURCE_DIR}/header)
#将源文件列表写在变量SrcFiles中
aux_source_directory(./src SrcFiles)
#设置可执行文件输出路径
set(EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/bin)
#设置可执行文件的名称,make之后bin目录下出现myprint.exe
add_executable(myprint ${SrcFiles})
2. 两种编译方法
方式一:自动配置
- 首先,按住Ctrl+Shift+P,输入CMake: Configure,配置CMake。
2. 配置完成后,在最下方会出现一条状态栏。先后执行Build和 run。 3. 成功输出
方式二:手动配置
# 1. 打开新的终端,在当前目录下,创建build文件夹
mkdir build
# 2. 进入到build文件夹下
cd build
# 3. 编译上级目录的CMakeLists.txt,生成Makefile和其他文件
cmake .. # Linux平台
cmake -G "MinGW Makefiles" .. # Windows平台
# 4. 执行make命令,生成target
make # Linux平台
mingw32-make.exe # Windows平台
3. F5自动调试
CMake多文件调试
想要F5自动调试需要配置json文件
- launch.json – for debug
- tasks.json – for build before debug
以上面的项目为参考进行相关文件配置
1. 配置c_cpp_properties.json文件
按住按住Ctrl+Shift+P,输入C/C++:Edit Configurations (UI),进行配置。
{
"configurations": [
{
"name": "Win32",
"includePath": [
"${workspaceFolder}/**",
"${workspaceFolder}/header"
],
"defines": [
"_DEBUG",
"UNICODE",
"_UNICODE"
],
"compilerPath": "D:\\Environment\\mingw64\\bin\\gcc.exe",
"cStandard": "gnu17",
"cppStandard": "c++11",
"intelliSenseMode": "windows-gcc-x64",
"configurationProvider": "ms-vscode.cmake-tools"
}
],
"version": 4
}
2. 配置任务tasks.json文件
按住按住Ctrl+Shift+P,输入Tasks: Configure Default Build Task,进行配置。
{
"version": "2.0.0",
"options": {
"cwd": "${workspaceFolder}\\build"
},
"tasks":[
{
"type": "shell",
"label": "cmake",
"command": "cmake",
"args": [
"-G",
"MinGW Makefiles",
".."
]
},
{
"label": "make",
"group": {
"kind": "build",
"isDefault": true
},
"command": "mingw32-make.exe",
"args": []
},
{
"label": "Build",
"dependsOn":[
"cmake",
"make"
]
}
]
}
3. 配置 launch.json文件
按下F5调试,进行launch.json文件配置。
{
"version": "0.2.0",
"configurations": [
{
"name": "(gdb) Launch",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}\\bin\\myprint.exe",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}\\bin",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"miDebuggerPath": "D:\\Environment\\mingw64\\bin\\gdb.exe",
"preLaunchTask": "Build",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
]
}
]
}
然后,按F5即可进行代码调试。
|