RunC和math.h的问题

时间:2012-02-22 20:33:54

标签: c runc

  

可能重复:
  Including files in C

我正在使用RunC编写一个需要pow和floor / truncate的简单函数。我包括math.h.当我使用main中的函数时,没有问题。但是,一旦我尝试创建一个单独的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

2 个答案:

答案 0 :(得分:0)

使用gcc编译程序:

gcc -lm -o foo foo.c

答案 1 :(得分:0)

在您的工作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,所以我还不能告诉你如何在数学库中链接,我试图找出答案。

我的谷歌太弱了。我没有在RunC上找到任何有用的文档,我也不打算安装Ubuntu来检查工具本身。