首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >RunC和math.h的问题

RunC和math.h的问题
EN

Stack Overflow用户
提问于 2012-02-22 20:33:54
回答 2查看 487关注 0票数 0

可能重复:

Including files in C

我正在使用RunC编写一个简单的函数,它需要pow和floor/truncate。我包括了数学。当我主要使用这些函数时,没有问题。但是,一旦我尝试创建一个单独的int函数,突然RunC就没有pow和floor函数了,并给出了一个错误。有什么帮助吗?

下面是代码: main()工作,但是如果我切换它来使用上面的函数来做完全相同的事情,它将不能工作。

代码语言:javascript
复制
#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));
}

这样做:

代码语言:javascript
复制
#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));
}

返回此错误:

代码语言:javascript
复制
/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
EN

回答 2

Stack Overflow用户

发布于 2012-02-22 21:08:07

使用gcc编写程序:

代码语言:javascript
复制
gcc -lm -o foo foo.c
票数 0
EN

Stack Overflow用户

发布于 2012-02-22 21:55:12

在工作的main函数中,您有

代码语言:javascript
复制
printf("%d", (int)pow(floor(sqrt(3)), 2));

注意,这里的参数是常量。优化编译器通常在编译时计算表达式,从而消除对math.h函数的调用,因此即使不链接数学库也能工作。但是,如果计算涉及变量,则通常不能在编译时对其进行计算,因此对math.h函数的调用保持不变,如果在数学库中没有链接,链接就会失败。试一试

代码语言:javascript
复制
#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中,命令行应该是

代码语言:javascript
复制
gcc -O3 -Wall -Wextra -o foo foo.c -lm

要链接的库应该放在命令行的最后一个,因为对于许多版本来说,如果在知道它们需要哪些符号之前就指定了它们,它就不能工作。

不幸的是,我根本不知道RunC,所以我还不能告诉你如何在数学库中连接它,我正在试图找出答案。

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9402475

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档