-1

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

Bart
  • 19,692
  • 7
  • 68
  • 77
  • 5
    What is the exact error ? How are you compiling your programs ? – cnicutar Feb 22 '12 at 17:07
  • @cnicutar: 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 complile. – user1222282 Feb 22 '12 at 17:13
  • That is a *linkage* problem, not an *include* problem. Check the answer by cnicutar. – karlphillip Feb 22 '12 at 17:17

1 Answers1

8

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:

cnicutar
  • 178,505
  • 25
  • 365
  • 392
  • I'm actually using RunC, so that does not apply to me. :( – user1222282 Feb 22 '12 at 19:45
  • 1
    "RunC is a simple (and somewhat crude) system that helps you use C++ as a scripting language under Unix." What we have here is evidence of that crudeness. You will need to figure out how to configure RunC to correctly link your script. – Steven Lu Feb 22 '12 at 19:58