编译链接的顺序
-l library
Search the library named library when linking. (The second alter-
native with the library as a separate argument is only for POSIX
compliance and is not recommended.)
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链接的时候是从左向右搜索的,foo.o -lz bar.o那么gcc的链接器先搜索库foo,然后是z库,然后是bar库。而链接搜索库的时候主要就是看当前用到了哪些函数和符合,比如当搜索到libz.so的时候只是把之前用到的函数和符合找出来,比如libz.so里面有两个函数 fa 和 fb,其中foo.o用到了fa,bar.o用到了fb,那么当搜索到libz.so的时候会把fa找出来,而fb就不要了,这样当连接到bar.o的时候就会因为缺少fb而报错。
所以我们要把底层库(即最可能被被人用到的库)放在最后,把应用层的库放在最前面。