开发者

help about place of header file in C [duplicate]

开发者 https://www.devze.com 2023-03-05 20:43 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: #include in .h or .c / .cpp ?
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

#include in .h or .c / .cpp ?

Can anyone explain to me the difference between including开发者_运维百科 a C header file in another header file or C source file in C ? How can the placement of header file includes affect code in the C language ?


It is considered good practice not to include any header files in your header files that you don't absolutely need to for the signatures of your functions (a form of hiding unnecessary details).

That said, any header file included in your header file will also be included in your source file, as the source file includes your header file (typing this is getting confusing :) ).


This might not be an easily answered question, since it influences your code design and propably the performance of your compilation.

First of, header files are read sequentially, so in the following example first.h would be read before second.h.

#include "first.h"
#include "second.h"

That means, that any definitions stated in first.h are also defined while reading second.h. Consider the following example:

In first.h the following is defined:

#define SOME_VERY_IMPORTANT_DEFINE

now if the second.h is read, see the following code:

#ifndef SOME_VERY_IMPORTANT_DEFINE
#include "third.h"
#endif

the third.h will not be included in your code, because SOME_VERY_IMPORTANT_DEFINE is defined and the conditional resolves to false.

Also, inclusions of header files are hierarchically, so all headers included in a header file, are also included in the source file that includes the header.

This is often used to provide an easy start into a library without having to scratch your head, which headers you need, because there is one header that includes all others.

I hope this helped a bit :)


Just understand that preprocessor is going to copy the headers to the source files if included and only sources files get compiled.

0

精彩评论

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