darksky
darksky

Reputation: 21019

Preprocessor #ifndef

Assume I have a.h which includes the following:

<stdbool.h>
<stddef.h>
<stdin.h>

Assume I also have b.h which also includes <stdbool.h>. If a.h has the #ifndef preprocessor definition statement in it and b.h doesn't. Will a.h include only what hasn't been included in b.h? So when b.h includes a.h, will a.h include stddef.h and stein.h and not re-include stdbool.h or are those preprocessor definition functions only used to see whether this whole class is redefined, and not specific functions within it?

EDIT:

Also, assume b.h includes another header file which includes stdbool.h -that makes b.h have stdbool.h both from that class and a.h. Will that cause errors?

Upvotes: 0

Views: 644

Answers (3)

qwertz
qwertz

Reputation: 14792

It's normal that most header start with

#ifndef _HEADERFILENAME_H_
#define _HEADERFILENAME_H_

and end with the following line:

#endif

If you include a header two times, the second time your programm won't include the full header again because of the #ifndef, #define and #endif

Upvotes: 0

Jens Gustedt
Jens Gustedt

Reputation: 78923

All C standard headers must be made such that they can be included several times and in any order:

Standard headers may be included in any order; each may be included more than once in a given scope, with no effect different from being included only once

Upvotes: 1

Bartosz Moczulski
Bartosz Moczulski

Reputation: 1239

If stdbool.h itself has include guards (#ifndef) then everything will be fine. Otherwise you may indeed end up including some headers twice. Will it cause a problem? It depends. If the twice-included header contains only declarations then everything will compile - it will just take few nanoseconds longer. Imagine this:

int the_answer(void); // <-- from first inclusion
int the_answer(void); // <-- from from second inclusion - this is OK
                      //       at least as long as declarations are the same

int main()
{
    return the_answer();
}

If on the other hand there will be definitions it will cause an error:

int the_answer(void)  // <-- from first inclusion - OK so far
{
    return 42;
}

int the_answer(void)  // <-- from second inclusion
{                     //     error: redefinition of 'the_answer'
    return 42;
}

int main()
{
    return the_answer();
}

Upvotes: 1

Related Questions