开发者

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


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.


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜