博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Ubuntu gcc错误:对'log'等函数未定义的引用
阅读量:6968 次
发布时间:2019-06-27

本文共 1201 字,大约阅读时间需要 4 分钟。

 

a.c 1 #include 
2 #include
3 int main() 4 { 5 float a; 6 void print_logarithm(double); 7 printf("enter a num:"); 8 scanf("%f",&a); 9 print_logarithm(a);10 return 0;11 }12 void print_logarithm(double x)13 {14 if(x<=0.0)15 {16 printf("Positive numbers only,please.\n");17 return;18 }19 printf("The log of x is %f",log(x));20 }

Ubuntu gcc编译

直接命令gcc -Wall a.c

1 tgs@tgs-VirtualBox:~$ gcc -Wall a.c2 /tmp/ccmKjOLq.o:在函数‘print_logarithm’中:3 a.c:(.text+0x97):对‘log’未定义的引用4 collect2: error: ld returned 1 exit status

查了一下发现:主要是C/C++编译为obj文件的时候并不需要函数的具体实现,只要有函数的原型即可。但是在链接为可执行文件的时候就必须要具体的实现了。验证如下:

1 tgs@tgs-VirtualBox:~$ gcc -Wall -c a.c2 tgs@tgs-VirtualBox:~$ gcc -Wall -o a a.o3 a.o:在函数‘print_logarithm’中:4 a.c:(.text+0x97):对‘log’未定义的引用5 collect2: error: ld returned 1 exit status6 tgs@tgs-VirtualBox:~$

编译时没有问题,链接生成可执行文件时报错。接下来加上-lm。 链接成功,如下:

1 tgs@tgs-VirtualBox:~$ gcc -Wall -o a a.o -lm2 tgs@tgs-VirtualBox:~$

注意1:-lm要加在编译文件后面。

这个主要的原因是gcc编译的时候,各个文件依赖顺序的问题。gcc编译的时候,如果文件a依赖于文件b,那么编译的时候必须把a放前面,b放后面。

注意2:sqrt()函数也是<math.h>头文件中的函数,但sqrt函数的使用没有以上限制,即编译时不加-lm也可以。

 

转载于:https://www.cnblogs.com/tgsAlex/p/7574408.html

你可能感兴趣的文章
[玩硬件]Arduino初级套试玩。
查看>>
Linux运维的8个小时工作时间都做什么
查看>>
Java学习日志(20-2-IO流-Properties与流合并切割)
查看>>
Andrioid 中 Service 组件的使用
查看>>
让Spring Controller 的方法基本数据类型参数支持Bean Validation
查看>>
mybatis.xml(理解的相对局限)
查看>>
详解VirtualBox虚拟机的四种网络设置
查看>>
关于学习区块链的推荐内容
查看>>
【腾讯bugly干货分享】HTML 5 视频直播一站式扫盲
查看>>
https原理通俗了解
查看>>
iOS开发debug集锦
查看>>
go-fasthttp源码分析
查看>>
RaspberryPi学习之SD卡文件修改及备份
查看>>
我的友情链接
查看>>
Java版InfluxDB工具类
查看>>
Python os/shutil/path 模块
查看>>
python学习笔记操作mongodb(九)
查看>>
[转]在A*寻路中使用二叉堆
查看>>
【Cloud Foundry 应用开发大赛】“17轻松”文章采集应用
查看>>
第七节 泛型(Generics)
查看>>