tags:

views:

82

answers:

4

Why do I have to specifically compile a C source file with:

gcc prog.c -lm

even when I have already included the specific header file with:

#include <math.h>
A: 

Because in C, there is technically absoultely no connection between the header file and the library. There can be more header files than libraries, or the other way round. It's just a matter of convention (and of course it makes some sense) to have a 1:1 relation in most cases.

ammoQ
+2  A: 

Because you need to inform the compiler which math library to link with, nothing to do with the math.h inclusion.

Otávio Décio
+4  A: 

The #include file tells the compiler how a function looks like, as in what type it returns, how many parameters of what types it takes, but it doesn't tell the compiler the contents.

The -lm flag includes that actual math library which contains the code for the functions to be called.

It works the same way with printf(), fread() and other standard functions. When you include stdio.h, you don't actually include the code of the function but the definitions. Because the C library is implicitly linked without you having to do anything about that, you don't notice it.

LukeN
But `<math.h>` is also part of the standard C library...
schot
It is, and I wish I could include why it isn't handled the same way (except for Windows)... but I don't know. The point gets across, tho :)
LukeN
+1  A: 

Similarly to your own code, which should have header files (.h) for function declarations and source files (.c) for function definitions, the code for the math library is in two parts. The header file, which you include, contains the function declarations:

double sqrt(double n);

However, it doesn't contain anything about how these functions work. This code is in a separate file which you have to link in, similarly to how you link different source files to create an application.

Samir Talwar