这很棘手...我不确定,但链接器可能会忽略 test.cpp 中 testfile::output() 的实现,因为标头 test.hpp 包含构造函数 testfile::testfile(int in) 的实现。
我实际上无法重现问题,试试这个:
test.hpp
#pragma once
using namespace std;
class testfile
{
private:
int i;
public:
testfile(int in);
void output();
};
test.cpp
#include "test.hpp"
#include <iostream>
using namespace std;
testfile::testfile(int in) : i(in) {}
void testfile::output()
{
cout << i << endl;
}
我认为最好将所有实现都放在上面的 *.cpp 文件中。
编辑:
我使用 g++ 编译这些文件(对不起,我没有 VScode 环境)。
命令行(正确):
g++ main.cpp test.cpp -o out
输出:
D:\workspace\test2\test2>out
main.cpp
5
命令行(不正确,缺少 test.cpp):
g++ main.cpp -o 输出
输出:
${User}\AppData\Local\Temp\ccYKJ92L.o:main.cpp:(.text+0x1a): undefined reference to `testfile::testfile(int)'
${User}\AppData\Local\Temp\ccYKJ92L.o:main.cpp:(.text+0x48): undefined reference to `testfile::output()'
collect2.exe: error: ld returned 1 exit status
命令行(不正确,缺少 main.cpp):
g++ test.cpp -o 输出
输出:
C:/Program Files/mingw-w64/x86_64-8.1.0-posix-seh-rt_v6-rev0/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/8.1.0/../../../../x86_64-w64-mingw32/lib/../lib/libmingw32.a(lib64_libmingw32_a-crt0_c.o):crt0_c.c:(.text.startup+0x2e): undefined reference to `WinMain'
collect2.exe: error: ld returned 1 exit status
EDIT2:
虽然我使用的是 windows,但我安装了 VSCode,但我想我知道为什么会出现这些类型的错误。
您可以使用 F6 命令构建带有 C/C++ 编译运行的源代码,但 F6 命令仅适用于当前选择并显示的文件在编辑器上。选择 main.cpp 则链接器找不到class testfile 的方法,否则选择 test.cpp 则链接器找不到项目的入口点(main)。
因此,如果您想正确构建,则必须制作某种构建脚本(makefile、json 等)。
如果你输入Ctrl+Shift+P,你可以输入Tasks: Configure task标签。单击它们并配置您的设置(主机操作系统,编译器,...)它将为您提供具有最小形式的默认 tasks.json 文件。
我使用这个 json 文件(Windows, mingw(gcc for windows))
tasks.json
{
"version": "2.0.0",
"command": "g++",
// compiles and links with debugger information
"args": ["-g", "-o", "out.exe", "main.cpp", "test.cpp"],
}
Ctrl+Shift+B(使用上面的json构建),然后输出:
running command> g++ -g -o out.exe main.cpp test.cpp
成功构建out.exe文件。
如果要调试或运行,请使用 F5 或 Ctrl+F5 或顶部菜单栏上的“调试”选项卡,然后其输出在调试控制台上:
main.cpp
5
调试或运行步骤指的是launch.json文件,就像构建步骤指的是tasks.json文件。
供参考,launch.json:
{
"version": "0.2.0",
"configurations": [
{
"name": "(Windows)build test",
"type": "cppvsdbg",
"request": "launch",
"program": "${workspaceFolder}/out.exe",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": false
}
]
}
Concolusionally 这不是来源的问题。
欲了解更多信息,请参阅这篇文章:
How do I set up Visual Studio Code to compile C++ code?