用 gcc link 库文件的顺序及 gcc 的使用方法
原则: 被调用的库函数总是放在最后。比如说 gcc -lm -lrt -lasound -ljack -L/usr/pkg/lib -lpthread -o test test1.c test2.c -lportaudio -L. 会报错。
两种解决方法:
1. gcc -lm -lrt -lasound -ljack -L/usr/pkg/lib -lpthread -o test test1.c test2.c libportaudio.a
2. gcc test1.c test2.c -o test -lm -lrt -lasound -lportaudio -L. -ljack -L/usr/pkg/lib -lpthread (首先test1.c 中文件调用了portaudio,所以portaudio一定要放在源文件后面。其次,portaudio可能调用了jack库里的函数, 所以 -lportaudio 一定要放在 -ljack 前面。
如果使用eclipse,link的顺序由 GCC C Linker->Libraries->Library search path(-L) 里的顺序决定。
gcc 使用方法: http://blog.csdn.net/zjf280441589/article/details/40019665
2.7.1 Link order of libraries
The traditional behavior of linkers is to search for external functions from left to right in the libraries specified on the command line. This means that a library containing the definition of a function should appear after any source files or object files which use it. This includes libraries specified with the short-cut -l
option, as shown in the following command:
$ gcc -Wall calc.c -lm -o calc (correct order)
With some linkers the opposite ordering (placing the -lm
option before the file which uses it) would result in an error,
$ cc -Wall -lm calc.c -o calc (incorrect order) main.o: In function `main': main.o(.text+0xf): undefined reference to `sqrt'
because there is no library or object file containing sqrt
after 'calc.c'. The option -lm
should appear after the file 'calc.c'.
When several libraries are being used, the same convention should be followed for the libraries themselves. A library which calls an external function defined in another library should appear before the library containing the function.
For example, a program 'data.c' using the GNU Linear Programming library 'libglpk.a', which in turn uses the math library 'libm.a', should be compiled as,
$ gcc -Wall data.c -lglpk -lm
since the object files in 'libglpk.a' use functions defined in 'libm.a'.
Most current linkers will search all libraries, regardless of order, but since some do not do this it is best to follow the convention of ordering libraries from left to right.
This is worth keeping in mind if you ever encounter unexpected problems with undefined references, and all the necessary libraries appear to be present on the command line.