【问题标题】:C++ Undefined Reference When Compiling .h and .cpp in Subfolders在子文件夹中编译 .h 和 .cpp 时的 C++ 未定义参考
【发布时间】:2020-12-16 16:28:59
【问题描述】:

长话短说,我想将我的 .h 和 .cpp 文件放在子文件夹中(分别为 include 和 src)并在我的 main.cpp 文件中引用它们,但我收到以下错误:

main.cpp:(.text+0x47): undefined reference to `Kmer::Kmer()'.

编译时使用:

g++ -I /path/to/MyFolder/include main.cpp.

我的文件结构如下:

  • 我的文件夹
    • main.cpp
    • 包括
      • Kmer.h
      • Kmer.cpp
//main.cpp
#include <iostream>
#include "Kmer.h"
using namespace std;

int main() {
    Kmer k;
    return 0;
};
//Kmer.h
#pragma once

class Kmer{
  public:
    Kmer();
  protected:
  private:
};
//Kmer.cpp
#include "Kmer.h"
#include <iostream>
using namespace std;

Kmer::Kmer(){
  // code here
  cout << "Kmer created" << endl;
}

感谢您的帮助!

【问题讨论】:

  • #include "Kmer.h" 也许你想要#include "include/Kmer.h"
  • 感谢您的回复!我这样做只是为了测试它,我收到了相同的错误消息。如果可能的话,我也更喜欢在 g++ 中使用 -I 命令,而不是在我的代码中使用相对路径。

标签: c++ compiler-errors g++ subdirectory


【解决方案1】:

您没有编译 Khmer.cpp。您需要将其添加到您的 g++ 编译行中

g++ -o <YOUR APPLICATION NAME> -I /path/to/MyFolder/include main.cpp src/Khmer.cpp

【讨论】:

  • 谢谢!小编辑正在将 src/Kmer.cpp 添加到 g++ 命令中!如果我使用这种方法,是否需要将每个 .cpp 文件添加到该命令进行编译? g++ -o &lt;YOUR APPLICATION NAME&gt; -I /path/to/MyFolder/include main.cpp src/Kmer.cpp
  • @DouglasFur 如果您有许多.cpp 文件,您通常会分别构建每个文件并将目标文件链接在一起作为最后一步。 Makefile 或 IDE 项目文件通常对此有所帮助,因此不会变得太多工作。
  • 如果您打算创建包含许多源文件的大型项目,我可以花点时间了解一下 makefile。
  • 谢谢!我肯定会研究 Makefiles。我开始将我的 python 库转换为 C++。你们对最好的 C++ 文档/资源有什么建议吗?
  • Bruh,在我使用此解决方案之前,我已经修补了 30 分钟。
猜你喜欢
  • 2023-03-13
  • 1970-01-01
  • 1970-01-01
  • 2018-01-30
  • 2014-07-25
  • 2022-10-15
  • 2019-04-17
  • 1970-01-01
  • 2011-03-13
相关资源
最近更新 更多