以c++为例,在D:\Code\test2工作目录有以下文件:
test.cc
#include <iostream>
#include "1\test1.h"
#include "2\test2.h"
using namespace std;
int main()
{
test1();
test2();
return 0;
}
test1.h
class t1
{
public:
t1(){};
virtual void f1();
};
test1.cc
#include <iostream>
#include "test1.h"
using namespace std;
void t1::f1()
{
cout << "f1" << endl;
}
test2.h
class t2
{
public:
virtual void f2();
};
test2.cc
#include <iostream>
#include "test2.h"
using namespace std;
void t2::f2()
{
cout << "f2" << endl;
}
tasks.json
{
"version": "2.0.0",
"tasks": [
{
"label": "echo",
"type": "shell",
"command": "g++",
"args": [
"-g",
"${workspaceFolder}\\*.cc",
"-o",
"${fileBasenameNoExtension}.exe",
"-fexec-charset=GBK"
]
},
],
}
此时运行是有问题的,终端显示undefined reference to `vtable for t2',undefined reference to `vtable for t1'.
这是因为在运行源文件时并没有同时编译task1.cc和task2.cc,那么头文件类中的函数都是未被定义的函数
将tasks.json修改如下:
{
"version": "2.0.0",
"tasks": [
{
"label": "echo",
"type": "shell",
"command": "g++",
"args": [
"-g",
"${workspaceFolder}\\*.cc",
"-g",
"${workspaceFolder}\\1\\*.cc",
"-g",
"${workspaceFolder}\\2\\*.cc",
"-o",
"${fileBasenameNoExtension}.exe",
"-fexec-charset=GBK"
]
},
],
}
修改后每次运行就相当于在终端输入g++ -g D:\Code\test2\*.cc -g D:\Code\test2\1\*.cc -g D:\Code\test2\2\*.cc -o test.exe -fexec-charset=GBK
每次运行时都会调试这三个文件目录下的.cc程序,其中-g 包括编译和链接两个步骤,并且在调试时生成调试信息 -o 指定输出文件名,*.cc表示上级文件目录下所有.cc文件,-g编译链接了三个源文件之后就可以运行了
同理,每有一个在不同目录下的文件就在后面添加"-g" "${workspaceFolder}\\(文件夹)\\*.cc"(workspaceFolder就是工作区文件夹)
如果要用到其他盘的文件夹或是包含源文件的文件夹在多个不同文件目录里,可以将该文件夹添加到工作区(在资源管理器里找到文件或文件夹,拖动到vscode资源管理器侧边栏,然后选择添加到工作区)
最后按上述方法添加即可。