文件目錄結構體為: src 和include 分別用來存放.cpp文件和 .hpp文件
其中:src文件夾下有需要的文件 simulator_client.cpp crc32.cpp ; include文件夾下有對應的頭文件 simulator_client.hpp、crc32.h及使用的頭文件cJSON.h
使用命令編譯時遇到如下問題:
g++ simulator_client.cpp -o simulator_client -lm -I../include
/tmp/ccZ5rfZQ.o: In function `packet_data(unsigned char, unsigned char, unsigned short, char*, unsigned int)':
simulator_client.cpp:(.text+0x228): undefined reference to `crc32'
simulator_client.cpp:(.text+0x27e): undefined reference to `crc32'
/tmp/ccZ5rfZQ.o: In function `create_package_json_info(package*, int)':
simulator_client.cpp:(.text+0x4e9): undefined reference to `cJSON_CreateObject'
simulator_client.cpp:(.text+0x512): undefined reference to `cJSON_CreateString'
........
collect2: error: ld returned 1 exit status
原因: 主要是C/C++編譯為obj文件的時候並不需要函數的具體實現,只要有函數的原型即可。但是在鏈接為可執行文件的時候就必須要具體的實現了。
如果錯誤是未聲明的引用,那就是找不到函數的原型,解決辦法這里就不細致說了,通常是相關的頭文件未包含。
使用命令 g++ simulator_client.cpp crc32.cpp -o simulator_client -lm -I../include 后
undefined reference to `crc32' 問題消失。
還有一個就是cjson庫的問題。在makefile中編譯時加入-lm動態庫是能夠查找到libcsjon.so連接庫的,但是不知為什么直接使用g++命令編譯卻找不到。
查看g++/gcc鏈接時查找路徑的規則:
1) -L指定的路徑,從左到右依次查找
2)由環境變量LIBRARY_PATH指定的路徑,使用":"分割從左到右依次查找
3)/etc/ld.so.conf指定的路徑
4)/lib 和 /usr/lib目錄下
在此我們查看3)中的路徑:
/usr/local/lib
在此路徑下我們可以看到cjson的庫文件為:(名稱為libcjson.so)
因此將編譯命令改為:
g++ simulator_client.cpp crc32.cpp -o simulator_client -I../include -lcjson
編譯通過。
參考地址: https://blog.csdn.net/cserchen/article/details/5503556