hue
hue

Reputation: 1779

Including header files more than once

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

int main ()
{
   printf ("hello world");
   return 0;
}

when I compile this, the compiler doesn't give any warning/error for including stdio.h twice. Why is it so? Aren't the functions scanf, printf etc. declared and defined twice now?

Thanks, in advance

Upvotes: 3

Views: 5031

Answers (4)

Satya
Satya

Reputation: 4478

No, the header files usually define a flag and then use #ifndef to include themselves only if the flag was undefined.

Open one up and see.

Upvotes: 0

davep
davep

Reputation: 286

As an aside, doing the "#ifndef" trick is appropriate for headers used by other people (like the standard headers).

If you need the #ifndef for a "private" program, then you are doing it "wrong". That is, you can and should organize headers within a project so they are not included more than once.

One reason that this is helpful is that keeps headers you think you have deleted from popping up again.

Since you can't control how public headers are used, this trick is reasonable for public headers. This trick is completely unnecessary for private headers.

Upvotes: -4

caf
caf

Reputation: 239041

In addition to the use of include guards, as pointed out by Mark Tolonen's answer, there is no problem with declaring a function more than once, as long as the declarations are compatible. This is perfectly fine:

int foo(int, char *);
int foo(int a, char *p);
extern int foo(int x, char y[]);

In fact, since every definition is also a declaration, whenever you "forward-declare" a function declared in the same file, you are declaring the function twice.

What is not OK is to create multiple external definitions of a function; but well-written header files should not create external definitions - only declarations. The (single) definition of the printf and scanf functions should be in an object file, which is linked with your program when it is built.

Upvotes: 2

Mark Tolonen
Mark Tolonen

Reputation: 177664

Typically, header files are written similar to the below example to prevent this problem:

#ifndef MYHEADER
#define MYHEADER

...


#endif

Then, if included more than once, then 2nd instance skips the content.

Upvotes: 11

Related Questions