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

竟然對執行時參數的位置都有要求,也是醉了

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章