开发者

Compiling with header files

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

gcc prog.c -lm

even when I have already in开发者_如何学Gocluded the specific header file with:

#include <math.h>


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.


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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜