有3个源文件,a.c b.c d.c,编译成目标文件a.o b.o d.o,编译成静态库libxxx.a。
有一个main文件,main.c,链接静态库,编译ok。
$ cc -o main main.c libxxx.a
如果直接链接静态库的目标文件,则报错:
$ cc -o main main.c a.o b.o d.o
wrs_assistant.c:(.text+0x280): undefined reference to `ev_timer_start'
当然实际的例子里面,不是a.c b.c d.c。上面为了简化使用简单的例子。
原因:
静态库的某个目标文件使用了未定义的函数。但是main.c实际上未使用这个目标文件中的函数,所以在作为静态库链接的时候,
根本没有链接这个目标文件。所以未报错。
而如果直接链接目标文件,ld会去链接这个目标文件。
链接过程:
Typically, on the linker command line, you will specify a set of object modules (that has been previously compiled) and then a list of libraries, including the Standard C Library. The linker takes the set of object modules that you specify on the command line and links them together. Afterwards there will probably be a set of "undefined references". A reference is essentially a function call. An undefined reference is a function call, with no defined function to match the call.
The linker will then go through the libraries, in order, to match the undefined references with function definitions that are found in the libraries. If it finds the function that matches the call, the linker will then link in the object module in which the function is located. This part is important: the linker links in THE ENTIRE OBJECT MODULE in which the function is located. Remember, the linker knows nothing about the functions internal to an object module, other than symbol names (such as function names). The smallest unit the linker works with is object modules.
参考:
http://www.nongnu.org/avr-libc/user-manual/library.html