Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Including header files more than once

Tags:

c

header-files

#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

like image 437
hue Avatar asked Dec 05 '25 08:12

hue


2 Answers

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.

like image 159
Mark Tolonen Avatar answered Dec 07 '25 20:12

Mark Tolonen


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.

like image 43
caf Avatar answered Dec 07 '25 20:12

caf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!