Dean
Dean

Reputation: 1153

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 convention 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

Upvotes: 0

Views: 3681

Answers (5)

ninjalj
ninjalj

Reputation: 43748

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

Upvotes: 2

davep
davep

Reputation: 90

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.

Upvotes: -1

Tom Zych
Tom Zych

Reputation: 13596

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.

Upvotes: 5

slartibartfast
slartibartfast

Reputation: 4456

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

Upvotes: 0

tamarintech
tamarintech

Reputation: 1992

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.

Upvotes: 1

Related Questions