在程序中用到某個靜態庫,使用命令:
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的相關描述