Including files in C

*爱你&永不变心* 提交于 2019-12-03 00:27:23

问题


I want to make a simple function involving sqrt(), floor() and pow(). So, I included <math.h>. When I try to use my function, my program says that sqrt() and floor() do not exist. I've triple checked my files and rewritten them, but it still gives the same error. Just to check if there was anything wrong with the <math.h> directory, I made another separate file that calculated the same thing and it worked. I am clueless right now. What am I doing wrong?

The code of the non functioning program:

#include <math.h>
#include "sumofsquares.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;
}

The working test file:

#include <stdio.h>
#include <math.h>

int main(void){
   printf("%d", (int)pow(floor(sqrt(3)), 2));
}

the error is this

/tmp/ccm0CMTL.o: In function sumofsquares': /home/cs136/cs136Assignments/a04/sumofsquares.c:9: undefined reference to sqrt' /home/cs136/cs136Assignments/a04/sumofsquares.c:9: undefined reference to floor' collect2: ld returned 1 exit status`

I am using runC on a virtual Ubuntu OS to compile


回答1:


You're probably missing the -lm argument to gcc, required to link the math library. Try:

gcc ... <stuff> ... -lm

There are at least two C FAQs relevant to your problem:

  • 14.3
  • 13.26


来源:https://stackoverflow.com/questions/9399480/including-files-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!