可能重复:
我正在使用RunC编写一个简单的函数,它需要pow和floor/truncate。我包括了数学。当我主要使用这些函数时,没有问题。但是,一旦我尝试创建一个单独的int函数,突然RunC就没有pow和floor函数了,并给出了一个错误。有什么帮助吗?
下面是代码: main()工作,但是如果我切换它来使用上面的函数来做完全相同的事情,它将不能工作。
#include <stdio.h>
#include <math.h>
int sumofsquares(int x){
int counter = 0;
int temp = x;
while (temp != 0 || counter == 100){
//temp = temp - (int)pow(floor(sqrt(temp)), 2);
//temp = temp - pow(temp, 0.5);
printf("%d\n", temp);
counter = counter + 1;
}
/*while(temp != 0){
temp = temp - (int)pow(floor(sqrt(temp)), 2);
counter ++;
}*/
return counter;
}
int main(void){
printf("%d", (int)pow(floor(sqrt(3)), 2));
}这样做:
#include <stdio.h>
#include <math.h>
int sumofsquares(int x){
int counter = 0;
int temp = x;
while(temp != 0){
temp = temp - (int)pow(floor(sqrt(temp)), 2);
counter ++;
}
return counter;
}
int main(void){
printf("%d", sumofsquares(3));
}返回此错误:
/tmp/cctCHbmE.o: In function `sumofsquares':
/home/cs136/cs136Assignments/a04/test.c:9: undefined reference to `sqrt'
/home/cs136/cs136Assignments/a04/test.c:9: undefined reference to `floor'
collect2: ld returned 1 exit status发布于 2012-02-22 21:08:07
使用gcc编写程序:
gcc -lm -o foo foo.c发布于 2012-02-22 21:55:12
在工作的main函数中,您有
printf("%d", (int)pow(floor(sqrt(3)), 2));注意,这里的参数是常量。优化编译器通常在编译时计算表达式,从而消除对math.h函数的调用,因此即使不链接数学库也能工作。但是,如果计算涉及变量,则通常不能在编译时对其进行计算,因此对math.h函数的调用保持不变,如果在数学库中没有链接,链接就会失败。试一试
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
int main(int argc, char *argv[]) {
// don't really use atoi, it's here just for shortness
int num = argc > 1 ? atoi(argv[1]) : 3;
printf("%d\n", (int)pow(floor(sqrt(num)),2));
return EXIT_SUCCESS;
}如果未在编译器命令行中指定要链接的数学库,也应该无法链接。
在gcc中,命令行应该是
gcc -O3 -Wall -Wextra -o foo foo.c -lm要链接的库应该放在命令行的最后一个,因为对于许多版本来说,如果在知道它们需要哪些符号之前就指定了它们,它就不能工作。
不幸的是,我根本不知道RunC,所以我还不能告诉你如何在数学库中连接它,我正在试图找出答案。
我的google-fu太弱了。我还没有在RunC上找到任何有用的文档,我也不打算安装Ubuntu来检查工具本身。
https://stackoverflow.com/questions/9402475
复制相似问题