-2

On an online C compiler called jdoodle, I tried this simple snippet below:

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

int main(void)
{
    double f = 1.2;
    //printf("%f\n", ceil(f));
    printf("%f\n", ceil(1.2));
    return 0;
}

It prints:

2.000000

Which is what I expected.

But when I change code to:

printf("%f\n", ceil(f));  
//printf("%f\n", ceil(1.2));

The compiler complains:

/tmp/ccv6kz5w.o: In function `main':
jdoodle.c:(.text+0x23): undefined reference to `ceil'
collect2: error: ld returned 1 exit status

Its fairly simple and clear from the man page for ceil() that it takes a double variable as the only argument.

When I changed the compiler version to 5.3.0 from 7.2.0, both codes were compiled successfully and generated the expected output.

Why is the updated version of compiler complaining about it then?

If compiler is right about complaining it, can anyone tell me why ceil(f); would be a problematic piece of code so that gcc-7.2.0 is not considering it valid, surprisingly assigning 'an undefined reference error' to a valid library function?

Update: I tried the same snippet with codechef online compiler with C-GCC6.3, it compiles fine and generates the expected output.

WedaPashi
  • 3,561
  • 26
  • 42
  • 1
    Add `-lm` when compiling. Check if it is there in the compile options in jDoodle – user2736738 Jan 05 '18 at 18:07
  • @Schwern: Possible duplicate, indeed. But I still have this question "Why is the updated version of compiler complaining about it then?" I might have to read the GCC docs for both version instead of asking anyone to do that for me. Thank you anyway :) – WedaPashi Jan 05 '18 at 18:14
  • If the online compiler were running on a Mac, the `-lm` would be harmless but unnecessary. There are differences between different systems. Te call with a literal is replaced at compile time so that there is no mention of `ceil()` in the executable — and no problems linking the code because the `-lm` library is missing. – Jonathan Leffler Jan 05 '18 at 18:20
  • The compiler could have calculated `ceil(1.2)` at compile time (so no need to actually make a call to `ceil` at runtime and thus linking with `-lm` isn't required). But it may not have been possible to do for `ceil(f)` (e.g., if `f` is a runtime input). So it requires `-lm`. In general, if you use math library functions, it's safe to link them - at worst it'll be ignored and harmless. – P.P Jan 05 '18 at 18:29

1 Answers1

1

The man page for ceil(3) document that:

you need to #include <math.h>

and that you should

Link with -lm.

You forgot to configure your online compiler to link with -lm; perhaps the one you are using don't offer such an option.

I recommend compiling on your own computer.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547