2015-09-03 27 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 
相关问题