GCC链接库的一个坑:动态库存在却提示未定义动态库的函数
背景
在GCC中已经指定链接库,然而编译时却提示动态库函数未定义!
测试出现的错误提示如下:
[GMPY@13:48 tmp]$gcc -o test -L. -lmylib test.c
/tmp/ccysQZI3.o:在函数‘main’中:
test.c:(.text+0x1a):对‘func_lib’未定义的引用
collect2: error: ld returned 1 exit status
而在测试用的动态库libmylib.so
中是有定义函数func_lib
的
[GMPY@13:55 tmp]$cat mylib.c
#include <stdio.h>
int func_lib(void)
{
printf("In share library\n");
return 0;
}
[GMPY@13:56 tmp]$gcc -fPIC -shared mylib.c -o libmylib.so
GCC的链接坑
在用gcc编译时,我们可以用-L
指定链接库位置,用-l
指定。
man gcc
查询时,我发现这么一段描述:
-llibrary
-l library
... ## 这里为了方便阅读,对原文进行了换行排版优化
It makes a difference where in the command you write this option;
the linker searches and processes libraries and object files in the order they are specified.
Thus, foo.o -lz bar.o searches library z after file foo.o but before bar.o.
If bar.o refers to functions in z, those functions may not be loaded.
...
嗯,这段话什么意思呢? 如果-l
链接库在源码之前,就会链接不到库!!
就像下面两个命令的差别:
异常:gcc -o test -L. -lmylib test.c
正常:gcc -o test -L. test.c -lmylib
竟然对执行时参数的位置都有要求,也是醉了