将单独的头文件和类定义文件链接到主函数文件 - G++ 返回重载"undefined reference to"构造函数

Linking separate header and class definition files to a main function file - G++ returns "undefined reference to" overloaded constructors

本文关键字:文件 重载 G++ 返回 undefined 构造函数 to reference 函数 单独 链接      更新时间:2023-10-16

我有5个文件,我正在尝试将其链接在一起;2个带有类声明的标题文件,2个带有类定义的CPP文件,1个带有主方法的文件

标题文件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文件,带有主方法

#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(int(定义。我一直在努力弄清楚,但我被击败了。感谢任何帮助,谢谢!

您不应在 .cpp 文件中使用#ifndef指令。我想您的 hash.h.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

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

如果您编译 main.cpp hash.cpp city.cpp 分别在 main.cpp 您应该放

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

而不是

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

没有此事,您将获得多个定义错误。