【问题标题】:Linker Error C++ "undefined reference " [duplicate]链接器错误 C++“未定义的引用”[重复]
【发布时间】:2013-01-11 12:47:39
【问题描述】:

可能重复:
What is an undefined reference/unresolved external symbol error and how do I fix it?

试图通过g++ -o prog1 main.cpp -std=c++0x编译我的程序

我得到错误:

/tmp/cc1pZ8OM.o: In function `main':
main.cpp:(.text+0x148): undefined reference to `Hash::insert(int, char)'
collect2: error: ld returned 1 exit status

ma​​in.cpp

#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <functional>
#include "Hash.h"

using namespace std;

int main(int argc, char *argv[]) {
//preset prime number 
int prime = 101;
hash<char> h1;
int key;
Hash HashTable;

// check for Request & string parameters
if(argc != 3) {
    cout << "Run program with 2 parameters. [Lower Case]" << endl;
    cout << "[1] insert, find, or delete" << endl;
    cout << "[2] string" << endl;
}

if(strcmp(argv[1], "insert") == 0) {
    //Get Hash for argv[2] aka value
    key = h1(*argv[2]);

    //check 1
    cout << "Hash: " << key << endl;

    key = key % prime;

    //check 2
    cout << "Mod 101 Hash: " << key << endl;

    HashTable.insert(key, *argv[2]); //PROBLEM here

}

return 0;
}

Hash.h 文件:

#include <iostream>
#include <cstring>
#include "LinkedList.h"
using namespace std;

class Hash {
//100 slot array for hash function
LinkedList *hashFN[100];

public:
void insert(int key, char value);
//void deleteItem(int key);
//char* find(int key);


};

有什么想法吗?使用它来构建具有设定大小的哈希表。

编辑:Hash.cpp文件

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

using namespace std;

void Hash::insert(int key, char value){
*hashFN[key]->addFront(value);
cout << "Success!" << endl;

}

现在尝试通过终端编译:

g++ -c Hash.cpp -o Hash.o

g++ -o prog1 main.cpp Hash.o -std=c++0x

不知何故进入了无限循环。

【问题讨论】:

  • Hash.cpp 文件在哪里? Hash::insert 函数的定义在哪里?
  • 认为问题在于您插入的是 char * 而不是 char。有同样的错误,但据我所知,一切看起来都很好。继续搜索....

标签: c++ reference undefined


【解决方案1】:

您的头文件 Hash.h 声明了“class hash 应该是什么样子”,但没有声明它的实现,它(可能)在我们将称为 Hash.cpp 的其他源文件中。通过在主文件中包含头文件,编译器会在编译文件时获知class Hash 的描述,而不是class Hash 的实际工作方式。当链接器尝试创建整个程序时,它会抱怨找不到实现 (toHash::insert(int, char))。

解决方案是在创建实际程序二进制文件时将所有文件链接在一起。使用 g++ 前端时,您可以通过在命令行上同时指定所有源文件来完成此操作。例如:

g++ -o main Hash.cpp main.cpp

将创建名为“main”的主程序。

【讨论】:

  • 如果我想分别编译两个文件,然后将它们链接在一起怎么办?链接器无法在第二个文件中找到函数,但是它们已在主文件中声明。看起来 Fox 写在橙色框中的 makefile 没问题,但是当我使用它时,它显示“未定义对 .... 的引用”
【解决方案2】:

这个错误告诉你一切:

对Hash::insert(int, char)的未定义引用

您没有链接到Hash.h 中定义的函数的实现。你没有Hash.cpp 来编译和链接吗?

【讨论】:

    【解决方案3】:

    您的错误表明您没有使用 insert 函数的定义编译文件。更新您的命令以包含包含该函数定义的文件,它应该可以工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-07-21
      • 2011-02-03
      • 1970-01-01
      • 2021-07-18
      • 1970-01-01
      相关资源
      最近更新 更多