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 }
直接命令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也可以。
原文:http://www.cnblogs.com/tgsAlex/p/7574408.html