Page 1 of 1

ANSI C not linking lm (math.h)

Posted: Mon Jun 15, 2015 10:32 pm
by danieldonadon
I tried to submit a program using ANSI C as compiler and I got the following compilation error:

Code: Select all

code.o: In function `main':
code.c:(.text.startup+0x54): undefined reference to `floor'
code.c:(.text.startup+0xac): undefined reference to `sqrt'
collect2: error: ld returned 1 exit status
It seems that the linker (ld) was not able to link the math library (lm). My code does include <math.h>, and it worked properly when submitted using C++ as compiler.

Since I've never noticed this problem before, I would guess that someone changed the compilation directive and omitted the "-lm" parameter. Is anyone aware of this problem?

Re: ANSI C not linking lm (math.h)

Posted: Tue Jun 23, 2015 7:13 pm
by squeekeek
Just happened to me a while ago when I was solving UVa 362. I received 10 compile errors and 7 wrong answers before I realized that the "ceil" function was the culprit. :x I just had to submit my code as C++ instead.

By the way, here's the compile error message. Oddly, it included an error to "scanf" too. I was pulling hairs because of this. :lol:

Code: Select all

code.c: In function 'main':
code.c:11:7: warning: ignoring return value of 'scanf', declared with attribute warn_unused_result [-Wunused-result]
  scanf("%d", &nsize);
       ^
code.c:21:10: warning: ignoring return value of 'scanf', declared with attribute warn_unused_result [-Wunused-result]
     scanf("%d", &nabytes[i]);
          ^
code.c:43:8: warning: ignoring return value of 'scanf', declared with attribute warn_unused_result [-Wunused-result]
   scanf("%d", &nsize);
        ^
code.o: In function `main':
code.c:(.text.startup+0xd6): undefined reference to `floor'
collect2: error: ld returned 1 exit status

Re: ANSI C not linking lm (math.h)

Posted: Wed Jun 24, 2015 1:55 am
by danieldonadon
Yes, it is quite disappointing that such problem would pass unnoticed.
squeekeek wrote:Oddly, it included an error to "scanf" too.
Actually it was not an error message, but a warning. The compiler was quite pedantic and notified you that the function scanf returns a value that should be used somehow in an expression. You don't have to do that, of course!

The function scanf (and others, like sscanf) returns the number of values correctly parsed from the input, or EOF (a macro constant) if the end-of-file was reached before reading. I find it useful to check this returned value so that I can ensure the input follows the specified description. I do this using the assert macro from <assert.h>, which aborts the program (and causes a Runtime Error) if the statement is false:

Code: Select all

assert(scanf("%d", &n) != EOF);