0

So I have searched around for a bit on the answer to this question, which is probably incredibly simple, but I haven't found anything yet, so here's the issue: Something like this code here works just fine:

int main(void){
    double x;
    x=ceil(5.5);
}

But if I try this:

int main(void){
    double x = 5.5;
    x=ceil(x);
}

I get this error message:

test.c:(.text+0x24): undefined reference to `ceil'

Why is this and how can I send a variable to function 'ceil()' and then store it in another variable?

codingEnthusiast
  • 3,800
  • 2
  • 25
  • 37
  • Your source file needs to include header `math.h`, and when you build your program you need to link in the math library. – John Bollinger Oct 07 '15 at 19:40
  • 4
    If the first one works but the second doesn't, I suspect the call to `ceil()` is being optimized out for the first case with the literal `5.5`. Otherwise, it should have the same error from not linking with the math library. – Dmitri Oct 07 '15 at 19:43

2 Answers2

5

Two things:

You need to #include <math.h> at the top of your file.

You need to link with the math library by passing -lm to gcc:

gcc -o myprog myprog.c -lm
dbush
  • 205,898
  • 23
  • 218
  • 273
  • This worked out just fine for me, thanks! I forgot to mention that I included the right libraries ( and ) but i'm kind of a noob here and didn't get the text app to format those include statements along with the rest of my code. – William Reed Oct 07 '15 at 20:45
  • @WilliamReed Glad I could help. Feel free to [accept this answer](http://stackoverflow.com/help/accepted-answer) if you found it useful. – dbush Oct 07 '15 at 20:49
1

Apart from including math.h, simply compile your file by writing -lm at the end of the command.

Since you are stating that your program sometimes work, maybe you are compiling your code differently at different times or some optimization takes place. Please take a look here (credits to dannas):

Archives (static libraries) are acted upon differently than are shared objects (dynamic libraries). With dynamic libraries, all the library symbols go into the virtual address space of the output file, and all the symbols are available to all the other files in the link. In contrast, static linking only looks through the archive for the undefined symbols presently known to the loader at the time the archive is processed.


If you specify the math library (which is usually a static one) before your object files, then the linker won't add any symbols.
codingEnthusiast
  • 3,800
  • 2
  • 25
  • 37