GCC连接库的一个坑:动态库存在却提示未定义动态库的函数

背景

在GCC中已经指定连接库,然而编译时却提示动态库函数未定义!shell

测试出现的错误提示以下:函数

[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查询时,我发现这么一段描述:this

-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连接库在源码以前,就会连接不到库!!code

就像下面两个命令的差异:ci

异常:gcc -o test -L. -lmylib test.c
正常:gcc -o test -L. test.c -lmylib

居然对执行时参数的位置都有要求,也是醉了源码

相关文章
相关标签/搜索