【问题标题】:Linking separate header and class definition files to a main function file - G++ returns "undefined reference to" overloaded constructors将单独的头文件和类定义文件链接到主函数文件 - G++ 返回“未定义的引用”重载构造函数
【发布时间】:2018-02-27 05:16:46
【问题描述】:

我有 5 个文件要链接在一起; 2个带有类声明的头文件,2个带有类定义的cpp文件,1个带有main方法的文件

头文件 1:city.h

#ifndef CITY_H
#define CITY_H

class City
{
// Class header code
}
#endif

定义文件 1:city.cpp

#include "City.h
#include <iostream>
#include <string.h>

#ifndef CITY_H
#define CITY_H
//Class definition code
#endif

这是我在编译时遇到错误的地方

头文件 2:hash.h

#include "City.h
#include <iostream>
#include <string.h>

#ifndef CITY_H
#define CITY_H
//Class definition code
#endif

定义文件 2:hash.h

#include "Hash.h"
#include <iostream>
#include <string.h>

#ifndef HASH_H
#define HASH_H
//Class definition
#endif

.cpp 文件和 Main 方法

#include "Hash.cpp"
#include "City.cpp"

using namespace std;
int main()
{
    int size;
    Hash* table = new Hash(size);

    return 0;
}

当我使用 g++ 编译时,出现以下错误:

/tmp/ccXGXFpg.o: In function 'main':
Project1.cpp:(.text+0x28): undefined reference to 'Hash::Hash(int)'
collect2: error: 1d returned 1 exit status

我真的不知道出了什么问题。 Hash 的构造函数被重载,因此有一个 Hash::Hash() 和 Hash::Hash(int) 定义。我一直想弄清楚,但我被打败了。非常感谢任何帮助,谢谢!

【问题讨论】:

  • 请提供minimal reproducible example。这包括但不限于:您的代码以及您如何调用编译器
  • 不相关:包含 cpp 文件是一个坏主意。不太可能与您当前的问题有关,但它通常会导致重复定义,因为 City.cpp 和 Hash.cpp 中的所有内容现在都在主 cpp 中重复。编译 City.cpp 和 Hash.cpp 并将它们与主 cpp 链接,您应该对 cpp 文件执行什么操作,将导致 City.cpp 和 Hash.cpp 中的所有内容的 2 个副本被找到两次。包括标题。编译和链接 cpp 文件。
  • 无论如何,您的实际问题无法通过提供的信息最终解决。投票结束。
  • .cpp 文件中删除 #ifndef#define#undef 指令。

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


【解决方案1】:

您不应在 .cpp 文件中使用 #ifndef 指令。我想你的 hash.h 文件有内容

#include "City.h
#include <iostream>
#include <string.h>

#ifndef HASH_H
#define HASH_H
//Class definition code
#endif

所以当hash.cpp文件编译时,其代码为

#include "Hash.h"   // [1]
#include <iostream>
#include <string.h>

#ifndef HASH_H   // [2]
#define HASH_H
//Class definition
hash::hash () {
     // ctor definition
}
#endif

[1]行的头文件内容被包含到.cpp文件中,并定义了HASH_H宏。在 [2] 行中,#ifndef 指令检查是否定义了 HASH_H,如果是,则忽略哈希类成员的所有定义,并且在链接器工作时会出现 undefined reference 错误。

如果你分别编译main.cpphash.cppcity.cpp,在main.cpp 你应该把

#include "city.h"
#include "hash.h"

而不是

#include "city.cpp"
#include "hash.cpp"

没有这个你会得到多个定义错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多