链接器未看到我的类.cpp

My Class.cpp is not being seen by the linker

本文关键字:我的 cpp 链接      更新时间:2023-10-16

我正在尝试使用 VS Code 作为我的 IDE,使用"run"和"C++"扩展名在单独的标头和 cpp 文件中编写一个 C++ 类。

主.cpp

#include "Fan.h"
int main() {
    Fan fan1;    
    return 0;
}

范·

#ifndef FAN_H
#define FAN_H
class Fan {
    public:
        Fan();
};
#endif

风扇.cpp

#include "Fan.h"
#include <iostream>
using namespace std;
Fan::Fan() {
    cout << "Fan Class" << endl;
}

我似乎真的找不到任何明显错误的东西。我想知道这是否是VS代码的设置问题。

如果我将 main #include"Fan.h"更改为"Fan.cpp".cpp它会起作用,因此它让我认为代码有效但链接器设置不正确。

将不胜感激任何帮助!

编辑:好的,所以我在不同的IDE中尝试了代码,它起作用了。这与VS Code有关。这是错误:

[Running] cd "c:Users<USER>DesktopFan" && g++ tempCodeRunnerFile.cpp -o tempCodeRunnerFile && "c:Users<USER>DesktopFan"tempCodeRunnerFile
C:Users<USER>AppDataLocalTempcclMFKxO.o:tempCodeRunnerFile.cpp:(.text+0x57): undefined reference to `Fan::Fan()'
collect2.exe: error: ld returned 1 exit status

听起来IDE只是在编译main.cpp。您需要找到正在编译main.cpp的命令,并确保它也将fan.cpp编译为 fan.obj 。您还需要确保将main.objfan.obj传递给链接器(链接器生成可执行程序、main.exe或其他任何内容(。

这里涉及两个步骤:

  1. cpp -> obj(将每个源文件编译为匹配的对象文件(
  2. obj -> exe(将许多目标文件链接到可执行文件中(
我会

说制作一个CMakeLists.txt文件并将main.cpp和fan.cpp添加到add_executable部分。然后VS可以通过CMake处理和运行文件。