将单独的头文件和类定义文件链接到主函数文件 - G++ 返回重载"undefined reference to"构造函数
Linking separate header and class definition files to a main function file - G++ returns "undefined reference to" overloaded constructors
我有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"
没有此事,您将获得多个定义错误。
相关文章:
- .h 文件中<<运算符重载
- 如何重载 << 运算符,以便将对象的数据写入文件?
- 包括来自另一个文件的运算符重载
- 如何让 + 重载在另一个文件C++中被识别?
- 如何在C++中包含头文件时错误地重载
- C++头/实现文件中的默认和重载构造函数?
- 从文件重载运算符>>读取单词
- 如何重载流运算符以使用位于不同文件中的函数
- 将单独的头文件和类定义文件链接到主函数文件 - G++ 返回重载"undefined reference to"构造函数
- 重载>>运算符以读取文本文件
- 重载 .h 文件中的'+'运算符,链接器错误
- 堆重载的2-D矩阵和c++中的读取文件
- C++头/实现文件和重载运算符
- 重载内存映射文件加载程序(C++)
- 重载运算符 '=' 和 [] 以写入文件中的位置
- 如何处理dervied类的多个重载,而不需要对其他文件进行多次更改
- 文件的 C++ 重载运算符 []
- 有关重载用于读取文本文件的输入运算符>>的问题
- 重载要输出到文件中的<<
- 在 c++ 头文件中声明重载运算符时遇到问题