Ubuntu gcc错误:对'log'等函数未定义的引用

 

a.c 
1
#include <stdio.h> 2 #include <math.h> 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.c
2 /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.c
2 tgs@tgs-VirtualBox:~$ gcc -Wall -o a a.o
3 a.o:在函数‘print_logarithm’中:
4 a.c:(.text+0x97):对‘log’未定义的引用
5 collect2: error: ld returned 1 exit status
6 tgs@tgs-VirtualBox:~$ 

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

1 tgs@tgs-VirtualBox:~$ gcc -Wall -o a a.o -lm
2 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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值