[问题]gcc关于静态库的问题

软件和网站开发以及相关技术探讨
回复
flea
帖子: 43
注册时间: 2007-01-31 1:11

[问题]gcc关于静态库的问题

#1

帖子 flea » 2007-08-27 10:39

今天看一本书关于gcc的链接器如何使用静态库来解析引用,书上说命令行上的库和目标文件的顺序非常重要,如果在命令行中,定义一个符号的库出现在引用这个符号的目标文件之前,那么引用就不能被解析,链接会失败。我查了一下gcc的manual,也是这么说的,但是我随便写了个程序
vim try.c

#include<math.h>
#include<stdio.h>

int main()
{
double i = 3.0;
printf("%f",log(i));

return 0;
}

gcc -lm try.c

怎么就没有错误出现呢,还可以正常编译
请各位指教
头像
madoldman
帖子: 599
注册时间: 2006-02-27 20:19
来自: works system
联系:

#2

帖子 madoldman » 2007-08-27 11:02

这是静态库吗?
东西路,南北走
十字路口人咬狗
拿起狗来打砖头
砖头咬了狗一口
图片
flea
帖子: 43
注册时间: 2007-01-31 1:11

#3

帖子 flea » 2007-08-27 12:21

不是吗,那是什么,/usr/lib/libm.a *.a这不就是静态库的格式吗
头像
madoldman
帖子: 599
注册时间: 2006-02-27 20:19
来自: works system
联系:

#4

帖子 madoldman » 2007-08-27 12:56

-lm是用的/usr/lib/libm.a吗?应该是/usr/lib/libm.so吧
东西路,南北走
十字路口人咬狗
拿起狗来打砖头
砖头咬了狗一口
图片
flea
帖子: 43
注册时间: 2007-01-31 1:11

#5

帖子 flea » 2007-08-27 13:32

-llibrary
-l library
Search the library named library when linking. (The second alternative 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.

The linker searches a standard list of directories for the library, which is actually a file named liblibrary.a. The linker then uses this file as if it had been specified precisely by name.

The directories searched include several standard system directories plus any that you specify with -L.

Normally the files found this way are library files—archive files whose members are object files. The linker handles an archive file by scanning through it for members which define symbols that have so far been referenced but not defined. But if the file that is found is an ordinary object file, it is linked in the usual fashion. The only difference between using an -l option and specifying a file name is that -l surrounds library with `lib' and `.a' and searches several directories.

这是gcc manual里的,你可以自己看啊
头像
madoldman
帖子: 599
注册时间: 2006-02-27 20:19
来自: works system
联系:

#6

帖子 madoldman » 2007-08-27 14:06

我怎么记得是优先动态的呢?我再查查看
东西路,南北走
十字路口人咬狗
拿起狗来打砖头
砖头咬了狗一口
图片
头像
madoldman
帖子: 599
注册时间: 2006-02-27 20:19
来自: works system
联系:

#7

帖子 madoldman » 2007-08-27 14:13

可以这样试一下,强制加上-static 或-shared来指定它使用静态的还是共享的
gcc -lm -static try.c
/tmp/ccKf5NIX.o: In function `main':
try.c:(.text+0x21): undefined reference to `log'
collect2: ld 返回 1
gcc -static try.c -lm
正确
gcc -lm -shared try.c
gcc -shared try.c -lm
也都正确
所以应该是默认共享库优先的
东西路,南北走
十字路口人咬狗
拿起狗来打砖头
砖头咬了狗一口
图片
flea
帖子: 43
注册时间: 2007-01-31 1:11

#8

帖子 flea » 2007-08-27 15:01

多谢,受教了
回复