【发布时间】: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++