您的位置:首页 > 其它

ld -l选项注意事项

2013-10-31 11:25 281 查看
在程序中用到某个静态库,使用命令:

gcc bin -llibrary.a object.o


结果发现找不到library.a中的某些函数符号

undefine reference to ...


通过nm命令查看library.a,发现该函数符号是存在的,说明library.a本身是没有问题的,百思不得其解,于是胡乱猜测,猜测可能是命令选项的顺序有问题,于是调整命令

gcc bin object.o -llibrary.a


编译成功,但是为什么呢?难道-l选项还有位置要求?于是通过man ld查看,-l选项描述得很少,但并没有提到-l位置的问题。于是百度得知:

http://hi.baidu.com/xiexin/item/2168cf28aca6d8ceddf69a47 (UNIX程序的链接)

链接程序对于静态库的搜索仅仅是为了解决以前发现的、尚未定义的外部引用。因此,-l选项在命令行中的位置很重要。例如:

$ cc -dn file1.c -lm file2.c

这样链接程序对libm.a的搜索只是为了解决file1.c中对数学函数的调用。因此如果在file2.c中调用了某个数学函数,链接程序将无法找到该函数的定义,因而链接也将失败。这种情况下,

除非是特别清楚每个C文件中都调用了哪些函数,否则还是将-l选项放在命令行的最后比较好,并且-l选项可以出现多次,以指定多个不同的库文件。


找到问题所在,这么重要的细节,gcc不可能不在文档里进行描述啊,于是再次man ld, 仔细看了一下,发现

This man page does not describe the command language; see the ld entry in "info" for full details on the command language and on other aspects of the GNU linker.


于是调用 info ld 命令,终于看到-l选项详尽的描述:

-l namespec
--library=namespec
Add the archive or object file specified by namespec to the list of
files to link.  This option may be used any number of times.  If
namespec is of the form :filename, ld will search the library path
for a file called filename, otherwise it will search the library
path for a file called libnamespec.a.

On systems which support shared libraries, ld may also search for
files other than libnamespec.a.  Specifically, on ELF and SunOS
systems, ld will search a directory for a library called
libnamespec.so before searching for one called libnamespec.a.  (By
convention, a ".so" extension indicates a shared library.)  Note
that this behavior does not apply to :filename, which always
specifies a file called filename.

The linker will search an archive only once, at the location where
it is specified on the command line.  If the archive defines a
symbol which was undefined in some object which appeared before the
archive on the command line, the linker will include the
appropriate file(s) from the archive.  However, an undefined symbol
in an object appearing later on the command line will not cause the
linker to search the archive again.

See the -( option for a way to force the linker to search archives
multiple times.

You may list the same archive multiple times on the command line.

This type of archive searching is standard for Unix linkers.
However, if you are using ld on AIX, note that it is different from
the behaviour of the AIX linker.


通过man gcc也能看到-l的相关描述
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: