Pregunta

I am programming a c project which must use the pow function defined in math.h. And when I tried to make the project, gcc gave the following link error: undefined reference to `pow'.

I know the -lm option must be added into my link instruction, but there are still several questions puzzling me.

Q1:When I pass two constants into pow function, link is successful without -lm. Why?

Q2:-lm being at the end or at the start of link instruction makes different results. gcc -lm $(OBJS) -o exbin is wrong, but gcc $(OBJS) -o exbin -lm is correct. Why?

I use ubuntu 11.10 and gcc 4.4.4.

Thanks! Please excuse my pool English.

¿Fue útil?

Solución

I cannot answer question 1 (that seems odd), but in regards to question 2 the reason gcc -lm $(OBJS) -o exbin does not work is because you must link things in order of useage. This is best explained by example:

/* File func_a.h */
/* Declare func_a */
void func_a();

/* File func_a.c */
#include "func_a.h"
void func_a()
{
    /* do stuff */
}

/* File func_b.c */
#include "func_a.h"
void func_b()
{
    /* Call func_a */
    func_a();
}

To properly link func_a and func_b into an executable, you must link them as gcc func_b func_a -o exec because func_b uses func_a. In short, you always want to link your library functions last.

Otros consejos

The compiler knows about pow(3, 4) or whatever, and optimizes the program by computing the result at compile time, so it doesn't need the library at link and run time.

A linker doesn't add stuff from a library unless it knows it needs it. With static libraries, that was strictly true. With shared libraries, some versions of the compilers would keep a note of all the symbols in all the shared libraries that were read, even if they weren't needed at the time when the library was scanned. More recent versions only take in shared libraries if at least one of the symbols is needed at the time when it is scanned. When the library comes first, the only symbol needed is main() (that's why main() is designated as the start point for a hosted environment), and therefore the maths library was ignored because there were no symbols in it that were needed.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top