用 gcc link 库文件的顺序及 gcc 的使用方法

本文详细解释了GCC编译器链接库文件时的正确顺序,并提供了两个具体的示例说明如何避免因链接顺序不当而导致的错误。文章还介绍了在Eclipse等IDE中如何设置正确的链接顺序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原则: 被调用的库函数总是放在最后。比如说 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.youkuaiyun.com/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.

转载于:https://www.cnblogs.com/sp4comm/p/4821428.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值