码迷,mamicode.com
首页 > 系统相关 > 详细

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

时间:2017-09-22 14:07:57      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:virt   scanf   math.h   clu   bsp   osi   文件的   void   引用   

 

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也可以。

 

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

标签:virt   scanf   math.h   clu   bsp   osi   文件的   void   引用   

原文地址:http://www.cnblogs.com/tgsAlex/p/7574408.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!