初学者makefile家伙试图找出问题所在。 在使我得到真正丑陋的错误
“对`Class :: Method(std :: __ cxx11 :: basic_string,std :: allocator>)的未定义引用””
也许有人可以帮助我了解这里的情况。当我将所有代码粘贴在一个大main.cpp文件中时,编译或运行代码都没有问题。但是,当我将代码分为各自的头文件和cpp文件时,我得到了所引用的丑陋错误。
Makefile
CXX = g++
CXXFLAGS = -Wall -g
main: main.o Hash.o
$(CXX) $(CXXFLAGS) -o main main.o
main.o: main.cpp Hash.cpp
$(CXX) $(CXXFLAGS) -c main.cpp
Hash.o: Hash.cpp Hash.h
$(CXX) $(CXXFLAGS) -c Hash.cpp
源代码
Main.cpp
#include "Hash.h"
#include <iostream>
int main() {
HashTable Hash;
std::string inputString = "Pot";
Hash.Add2Hash(inputString);
std::string returnVal = Hash.GetHashValue(inputString);
std::cout << returnVal << std::endl;
}
Hash.h
#include <string>
#define HASH_SIZE 100000
typedef unsigned int uint_t;
struct HashElement_t{
HashElement_t * Next;
std::string Value;
uint_t Key;
};
class HashTable {
private:
HashElement_t * HashArr[HASH_SIZE];
public:
void Add2Hash(std::string InsertionValue);
uint_t GenerateHashIndex(char * c);
std::string GetHashValue(std::string KeyValue);
};
Hash.cpp
#include "Hash.h"
#include <string>
void HashTable::Add2Hash(std::string InsertionValue) {
uint_t HashIndex = GenerateHashIndex(&InsertionValue[0]);
HashElement_t * InsertionElement = new HashElement_t;
HashElement_t * HashPosition = HashArr[HashIndex];
InsertionElement->Key = HashIndex;
InsertionElement->Value = InsertionValue;
InsertionElement->Next = NULL;
if(HashPosition != NULL) {
while (HashPosition->Next != NULL) {
HashPosition->Next = InsertionElement;
HashPosition = HashPosition->Next;
}
}
this->HashArr[HashIndex] = InsertionElement;
}
uint_t HashTable::GenerateHashIndex(char * c) {
uint_t val{10};
while (*c != NULL) {
val *= *c;
c++;
}
return val % HASH_SIZE;
}
std::string HashTable::GetHashValue(std::string KeyValue) {
uint_t HashIndex = GenerateHashIndex(&KeyValue[0]);
return this->HashArr[HashIndex]->Value;
}
错误消息
$ make
g++ -Wall -g -c main.cpp
g++ -Wall -g -o main main.o
main.o: In function `main':
C:\Users\Name\Documents\Coding\Leet Coding/main.cpp:9: undefined reference to `HashTable::Add2Hash(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >)'
C:\Users\Name\Documents\Coding\Leet Coding/main.cpp:10: undefined reference to `HashTable::GetHashValue(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >)'
collect2.exe: error: ld returned 1 exit status
make: *** [Makefile:5: main] Error 1