出現的問題:
在使用 make 編譯實現一個程序時,出現了下面的錯誤。查看程序源文件所在的目錄時發現程序已經完成了編譯,並生成了 list_repo.o 的文件,說明是在程序鏈接生成可執行文件時發生了問題。
storages/local.o:在函數‘LocalStorage::init(std::map<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::less<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<std::pair<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >&)’中: local.cc:(.text+0x2dae):對‘Getload::get_load(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >&)’未定義的引用 collect2: error: ld returned 1 exit status Makefile:32: recipe for target 'bin/list_repo' failed make: *** [bin/list_repo] Error 1
出錯原因及解決過程:
1、出錯原因:在要編譯鏈接的源文件 list_repo.cc 中缺少了一個需要引用的頭文件 getload.h 的聲明;
解決過程:在要實現的源文件中添加所要用到的所有的頭文件。在本例中添加 getload.h 的頭文件后再次嘗試編譯,發現錯誤並沒有消失,23333,好氣呀,還以為解決的思路有問題。。。。。走了半天彎路,發現了下面的錯誤。
2、出錯原因:在 Makefile 文件的編輯時沒有將關聯引用的文件 getload.cc 添加上。。。。。好蠢啊。。。。。
解決過程:
LS_SRCS=list_repo.cc xxxxx.cc xxxxx.cc getload.cc xxxxx.cc xxxxx.cc
在 Makefile 文件中添加引用文件 getload.cc 后,再次編譯終於通過,開心!!!!!
g++ -o bin/list_repo list_repo.o xxxxxx.o xxxxx.o getload.o xxxxx.o xxxxx.o -O3 -Wall -L../xxxxx/lib -L../xxxxx/lib -lpthread
參考文章:
1、烏合之眾:gcc編譯時對’xxxx’未定義的引用問題 寫的很詳細;
2、知乎問答:g++鏈接時報錯:未定義的引用? 和我的問題不一樣,是使用模塊類時出現的問題。