开发者

Tips on using preprocessor #ifndef

I'm learning C and hope someone can explain what's the logic of using #ifndef?

I also find many C programs I looked, people seems following a co开发者_StackOverflow中文版nvention using the filename following the #ifndef, #define and #endif. Is there any rule or tip on how to choose this name?

#ifndef BITSTREAM_H
#define BITSTREAM_H

#include <stdio.h>
#include <stdint.h>

/*Some functions*/

#endif


Header files will often use logic like this to avoid being included more than once. The first time a source file includes them, the name isn't defined, so it gets defined and other things are done. Subsequent times, the name is defined, so all that is skipped.


The one you posted, in particular, is called an Include Guard.


The term for what you're looking for is Preprocessor Directives.

#ifndef doesn't need to be followed by a filename, for example it's common to see #ifdef WINDOWS or #ifndef WINDOWS, etc.


#ifndef means "if not defined". It is commonly used to avoid multiple include's of a file.


Tom Zych: "Header files will often use logic like this to avoid being included more than once."

This is true but it really is only necessary for "public" headers, like headers for library functions, where you don't have any control over how the headers are included.

This trick is unnecessary for headers used in projects where you have control over how things are included. (If there's a use for them outside of public headers, it's not a common one).

If you avoid using them in "private" headers, you'll more likely include headers in a less haphazard way.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜