“未定义参考"到静态库中定义的函数 [英] "Undefined reference " to a function defined in static library
问题描述
我正在尝试构建要在应用程序中使用的库.我按如下所示构建了库,并且在编译应用程序时出现以下错误:
I am trying to build a Library to use in an application. I built the library as below, and when i compile the application i get the below error:
我做过以下事情.
我使用:
gcc version 4.6.3 (Ubuntu/Linaro 4.6.3-1ubuntu5)
在要从应用程序调用的库中:
这里我有很多模块,但是这个库的入口是func() (即main()替换为func(),以便我可以调用该模块,而且func()也未声明为静态".)
In Library to be called from application:
Here i have lot of modules, but entry point to this library is func() (i.e., main () is replaced with func() so that i can call the module, also func () is not declared as 'static'.)
在一个文件中:
int func ();
...
int func ()
{ ... }
然后将库构建为:
gcc -Wall file.c -o file.o
...
...
ar rvs libfun.a $(OBJS)
还分别在libfun.a上使用了ranlib和nm -s来构建符号表, 但是使用这些命令后,归档文件的总大小没有变化,但仍然出现链接错误. $(OBJS)包含所有目标文件
Also used ranlib and nm -s on libfun.a seperately to build symbol table, but the total size of archive did not change after using these commands and still got the linking error. Here $(OBJS) contains all the object files
extern int func();
extern int func ();
编译为:
gcc -Wall -L./path-to-lib -lfun -o appl
然后我得到以下错误:
In function `main':
undefined reference to `func()'
collect2: ld returned 1 exit status
我试图用"ar s"和"ranlib"构建符号表,但是结果是相同的.
I tried to build symbol table with "ar s" and "ranlib" but the results is same.
我观察到的一件事是,我构建的"ar"的内容与项目中已经存在的其他模块的存档存在差异.
One thing i observed is there is a difference in contents of "ar" which i built and the archives already present in project for other modules.
我创建的档案包含(带有"nm -s libfun.a"的输出):
The archive built by me contains (ouput with "nm -s libfun.a" ):
Archive index:
Cfg1 in f1.o
mCfg1 in f1.o
dpCfg in f1.o
但是我使用的其他没有任何更改的档案文件包含以下奇怪的模式:
But the other archives which i am using without any changes contain below strange pattern:
Archive index:
_Z29platformSetjP38tagTCPIP_INTERFACE_INSTANCE_ATTRIBUTES in platform.o
_Z27platformTestSetTcpjP20tagTCPIP_CONFIG_DATAPh in platform.o
_Z23platformSetTcpIpjP20tagTCPIP_CONFIG_DATA in platform.o
我不确定上面有什么区别.是共享库还是静态库?
I am not sure what is the difference above. Is it a shared Library or a Static library ?
我正在尝试使用GCC进行编译,并使用'ar'建立档案,但是其他库文件可能正在使用g ++编译器.我不知道.以防万一.
I am trying to compile with GCC and build archive with 'ar', but the other library files may be using g++ compiler. I am not sure. Just in case it matters.
在构建图书馆时,我在这里做错了什么?请帮忙吗?
What am i doing wrong here in building my library ? Please help?
致谢.
推荐答案
我发现了错误的原因. 我将静态库与其他使用位置独立代码(PIC)和其他标志编译的库混合使用.添加这些标志可以解决此问题.
I found out the reason for the error. I was mixing the static library with other libraries compiled with position independent code (PIC) and some other flags. Adding these flags solved the issue.
这篇关于“未定义参考"到静态库中定义的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!