g++编译时遇到问题undefined reference to

文件目录结构体为: 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

posted @ 2019-05-22 09:45  hbg-rohens  阅读(16879)  评论(0编辑  收藏  举报