网上也没找到详细的介绍,自己记录一下.
1.文件结构
Add.h、Add.cpp、main.cpp放在同一文件夹下
// Add.h
#include<iostream>
using namespace std;
int add(int a, int b);
//Add.cpp
#include<iostream>
#include"Add.h"
using namespace std;
int add(int a, int b)
{
return a+b;
}
//main.cpp
#include<iostream>
#include"Add.h"
using namespace std;
int main(){
int a = 10;
int b = 20;
int c;
c = add(a, b);
cout<<a<<" + "<<b<<" = "<<c<<endl;
return 0;
}
2.VS Code 配置
- vscode 菜单栏 Terminal > Configure Default Build Task>C/C++: g++ build active file.
在.vscode下生成tasks.json,修改
//tasks.json
{
"version": "2.0.0",
"tasks": [
{
"type": "shell",
"label": "shell: g++ build active file",
"command": "/usr/bin/g++",
"args": [
"-g",
"${file}",
"${workspaceFolder}/Add.cpp", //这里添加引用的.cpp一起编译
"-o",
"${fileDirname}/${fileBasenameNoExtension}"
],
"options": {
"cwd": "/usr/bin"
},
"problemMatcher": [
"$gcc"
],
"group": "build"
}
]
}
3.运行
1.
- VS Code : Ctrl+Shift+B 生成main文件
- terminal: ./main
2.
-
也可以直接在VS Code:F5 > C++ (GDB/LLDB) > g++ build and debug active file,生成launch.json.
-
可能会报错,tasks.json->tasks里多出一段代码,有两个task:"label"不同:
"label": "shell: g++ build active file", "label": "g++ build active file",
-
launch.json里改成对应的task
"preLaunchTask": "shell: g++ build active file",
-
F5应该就可以了.