【发布时间】:2021-06-12 05:09:27
【问题描述】:
我编写了一个代码,其中包含一个存在于命名空间中的类。
这是头文件:如您所见,该类是在命名空间内创建的,在 frileg.h 中。
namespace frileg
{
class legeplads
{
public:
int x;
int y;
int z;
void print();
};
}
然后我还在legeplads.cpp中定义了函数print():
void frileg::legeplads::print()
{
std::cout << "pos: {" << x << ", " << y << ", " << z << "}" << std::endl;
}
但是当我在 main 函数中运行代码时,我得到一个错误:“undefined reference to `frileg::legeplads::print()':”
int main(){
legeplads a;
a.x = 1;
a.y = 2;
a.z = 3;
a.print();
return 0;
}
【问题讨论】:
-
您是否修改了
tasks.json以使 Visual Studio Code 将多个源文件编译到您的可执行文件中。 VSCode 的默认行为是只构建活动文件,所以如果你有 2 个 cpp 文件并且你没有修改你的 tasks.json 预计会出现链接器错误。 -
我该怎么做?
-
"command": "C:\\DEV\\MinGW\\bin\\g++.exe", "args": [ "-g3", "-Wall", "${file }", "-o", "${fileDirname}\\${fileBasenameNoExtension}.exe" ], "options": { "cwd": "${workspaceFolder}" },
-
应该编辑哪一部分?
-
VSCode 的文档在这里解释了如何使用多个源文件进行编译:https://code.visualstudio.com/docs/cpp/config-mingw#_modifying-tasksjson
标签: c++ class visual-studio-code namespaces