2015-09-03 52 views
1

對於以下示例,我得到一個undefined reference錯誤。我已經看到了很多的問題,涉及到這個問題,但認爲我給了一個精簡的,可重複,概念例如在其他問題而不是具體的問題,未定義的引用錯誤,但存在於庫中的符號

dynlib.h:

void printMe_dyn(); 

dynlib.c:

#include <stdio.h> 
#include "dynlib.h" 

void printMe_dyn() { 
    printf("I am execuded from a dynamic lib"); 
} 

myapp.c:

#include <stdio.h> 
#include "dynlib.h" 

int main() 
{ 
    printMe_dyn(); 
    return 0; 
} 

構建步驟:

gcc -Wall -fpic -c dynlib.c 
gcc -shared -o libdynlib.so dynlib.o 
gcc -Wall -L. -ldynlib myapp.c -o myapp 

錯誤:

/tmp/ccwb6Fnv.o: In function `main': 
myapp.c:(.text+0xa): undefined reference to `printMe_dyn' 
collect2: error: ld returned 1 exit status 

證明,符號庫:

nm libdynlib.so | grep printMe_dyn 
00000000000006e0 T printMe_dyn 
  1. 我使用了正確的編譯器標誌構建動態 庫?
  2. 我提出的證據確實是一個明確的證據嗎?
  3. 還有什麼其他方法可以診斷問題?

回答

1

庫的出現順序事情

引述online gcc manual

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.

你應該改變你的彙編語句來

gcc -o myapp -Wall -L. myapp.c -ldynlib 

告訴gcc搜索中使用的符號(編譯)myapp.c存在於dynlib

1

鏈接器命令行中庫的順序很重要。修復:

gcc -o myapp -Wall -L. myapp.c -ldynlib 
相關問題