链接器错误C++"未定义引用"

Fox*_*Fox 30 c++ reference undefined

可能重复:
什么是未定义的引用/未解析的外部符号错误,如何解决?

试图通过编译我的程序 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
Run Code Online (Sandbox Code Playgroud)

main.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;
}
Run Code Online (Sandbox Code Playgroud)

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);


};
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?使用它来构建具有set size的哈希表.

编辑: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;

}
Run Code Online (Sandbox Code Playgroud)

现在尝试通过终端进行编译:

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

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

它以某种方式进入无限循环.

she*_*heu 38

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

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

g++ -o main Hash.cpp main.cpp
Run Code Online (Sandbox Code Playgroud)

将创建名为"main"的主程序.

  • 如果我想分别编译两个文件然后将它们链接在一起怎么办?链接器无法在第二个文件中找到函数,但是它们已在主文件中声明。看起来Fox的makefile在橙色框中已经可以了,但是当我使用它时,它说“对...的未定义引用”。 (3认同)

Kos*_*Kos 25

这个错误告诉你一切:

undefined reference toHash :: insert(int,char)

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