math中的sin、cos等函数加载问题小议

软件和网站开发以及相关技术探讨
回复
weihua2008
帖子: 448
注册时间: 2008-07-10 15:08

math中的sin、cos等函数加载问题小议

#1

帖子 weihua2008 » 2008-07-11 11:56

函数 sin,未在本程序中定义也不在默认库‘libc.a’中;除非被指定,编译器也不会链接‘libm.a’。

为使编译器能将 sin 链接进主程序‘calc.c’,我们需要提供数学库‘libm.a’。一个容易想到但比较麻烦的做法是在命令行中显式地指定它:

代码:
$ gcc -Wall calc.c /usr/lib/libm.a -o calc


函数库‘libm.a’包含所有数学函数的目标文件,比如sin,cos,exp,log及sqrt。链接器将搜索所有文件来找到包含 sin 的目标文件。

一旦包含 sin 的目标文件被找到,主程序就能被链接,一个完整的可执行文件就可生成了:
在出此使用gcc编译运行一个简单的c程序时有这样的问题:
#include<stdio.h>
#include<math.h>
int main(void)
{
double x= sin(3.5);
printf("cos(3.5)=%f\n",x);
return 0;
}
$ gcc -Wall sin.c -o sin4
提示错误:
/tmp/ccuEfQUC.o: In function `main':
sin.c:(.text+0x1b): undefined reference to `sin'
collect2: ld 返回 1
经各位同仁的指点,有的教我安装libc6-dev。
我试了没装成,还有的教我安装build-essential
也不成。
最后我查到一位大哥说

代码:gcc -Wall sin.c /usr/lib/libm.a -o sin4
$ ./sin4
The value of sin(2.0) is 0.909297

非常感谢

可执行文件包含主城许的机器码以及函数库‘libm.a’中 sin 对应的机器码。

为避免在命令行中指定长长的路径,编译器为链接函数库提供了快捷的选项‘-l’。例如,下面的命令

代码:
$ gcc -Wall calc.c -lm -o calc


与我们上面指定库全路径‘/usr/lib/libm.a’的命令等价。

同样我试了cos函数都没问题!
学无止境
zarra
帖子: 89
注册时间: 2006-10-30 20:01

#2

帖子 zarra » 2008-07-11 12:24

你用ldd 看看
-lm 一般gcc默认连接到动态库 libm.so
/usr/lib/libm.a 显然是静态库了。。。。
头像
kofshower
帖子: 1343
注册时间: 2007-03-13 11:23
联系:

#3

帖子 kofshower » 2008-07-11 12:26

-lm就ok
"We are all in the mud, but some of us are looking at the stars." (Oscar Wilde)
We are not born for ourselves.
人生天地间,并非为自己
Homepage:http://sites.google.com/site/polarisnotme/
weihua2008
帖子: 448
注册时间: 2008-07-10 15:08

#4

帖子 weihua2008 » 2008-07-11 17:51

kofshower
哥们对epoll认识多少,给讲讲,最好举例说明一下
学无止境
头像
kofshower
帖子: 1343
注册时间: 2007-03-13 11:23
联系:

#5

帖子 kofshower » 2008-07-11 18:37

就不重复发帖了
viewtopic.php?p=836115#836115
"We are all in the mud, but some of us are looking at the stars." (Oscar Wilde)
We are not born for ourselves.
人生天地间,并非为自己
Homepage:http://sites.google.com/site/polarisnotme/
weihua2008
帖子: 448
注册时间: 2008-07-10 15:08

#6

帖子 weihua2008 » 2008-07-12 11:06

有没有这方面的书,推荐一下
weihua2008
帖子: 448
注册时间: 2008-07-10 15:08

#7

帖子 weihua2008 » 2008-07-12 11:06

有没有这方面的书,推荐一下
weihua2008
帖子: 448
注册时间: 2008-07-10 15:08

#8

帖子 weihua2008 » 2008-07-12 11:08

关于math的那个是用-lm
我写错了,抱歉,
不过代码里是对的
weihua2008
帖子: 448
注册时间: 2008-07-10 15:08

#9

帖子 weihua2008 » 2008-07-12 14:52

kofshower
我知道epoll有三个函数,但是不会用,
头像
kofshower
帖子: 1343
注册时间: 2007-03-13 11:23
联系:

#10

帖子 kofshower » 2008-07-12 18:17

I have read some essay.
Appears in the Proceedings of the Ottawa Linux Symposium, Ottawa, Canada, July, 2004
Comparing and Evaluating epoll, select, and poll Event Mechanisms
Scalable network I/O in Linux
"We are all in the mud, but some of us are looking at the stars." (Oscar Wilde)
We are not born for ourselves.
人生天地间,并非为自己
Homepage:http://sites.google.com/site/polarisnotme/
回复