tags:

views:

93

answers:

3

I cannot understand why this throws undefined reference to `floor'":

double curr_time = (double)time(NULL);
return floor(curr_time);

Hasn't it been casted to double, which is what floor receives?

+5  A: 

Maybe because you don't link with the math library? The error has nothing to do with casts and data types, btw.

wRAR
What I do not understand is why, without linking with the math library either, things like floor(1.2) _do_ worked. That is why I thought the error was related to the data type.
plok
@plok: Maybe it worked, because you were on a different system? Sometimes, the library is linked by default.
Lucas
@Lucas: it was on the same system, without modifying anything. I just tried with a simpler statement when the error was thrown and saw that floor(1.2) worked. Is it possible that the result is being calculated by gcc at compile time?
plok
@plok: Yes. GCC will evaluate `floor(1.2)` at compile time.
Stephen Canon
+7  A: 

You possibly have run in to the infamous -lm problem: Compile as:

gcc yourfile.c -o out -lm 

This is C FAQ 14.3 item as well.

dirkgently
Library linking flags should go after sources and object files, btw.
wRAR
+2  A: 

You probably have to link explicitly to the library. On an UNIX-like system this would typically be "/usr/lib/libm.a". The C standard library should be linked by default, but the math library is, depending on your system, not linked and you may have to link explicitly. (e.g. on Mac OS X it is also linked by default on my ubuntu system it is not).

Note that this has nothing to do with your include path. If you are on something UNIX-like you will probably find the header with the prototype declaration under "/usr/include/math.h", where your compiler will always look for headers.

If you are using gcc, you can either link directly with:

gcc yourfile.c /usr/lib/libm.a -o out

or with "-l*nameroflibrary*" like this:

gcc yourfile.c -lm -o out

this will look for a library in the same directory as the C standard library with the name "lib*nameoflibrary*.a"

Lucas