1

Most header file wrap their content as such:

#ifndef MY_HEADER_H
#define MY_HEADER_H

// header body...

#endif MY_HEADER_H

If this was removed, would it cause issues when including the header file in multiple source files? or is the preprocessor smart enough to ignore it? (I know it causes issues when it's included multiple times in the same source file)

Joe
  • 11
  • 1
  • These are called [include guards](https://en.wikipedia.org/wiki/Include_guard) and since C and C++ come from times where processor time was more valuable than programmer time, you still better use them. – Robert Feb 19 '19 at 02:03
  • Supplementary reading: [How does the compilation/linking process work?](https://stackoverflow.com/questions/6264249/how-does-the-compilation-linking-process-work) – user4581301 Feb 19 '19 at 02:07

3 Answers3

3

If this was removed, would it cause issues when including the header file in multiple source files?

No. It might cause issues when including the header file in the same source file more than once.

or is the preprocessor smart enough to ignore it?

No. The preprocessor doesn't know about more than one source file at a time.

user253751
  • 57,427
  • 7
  • 48
  • 90
2

If this was removed, would it cause issues when including the header file ...

Potentially, yes. Not necessarily. In general, it depends. In particular, it depends on the content of the header and whether the header is included more than once into a single translation unit (TU). Some declarations can be repeated - others may not. For example, definitions must not be repeated.

... in multiple source files?

Whether the header has guard macro is irrelevant to the header being included into multiple TUs. Each TU is pre-processed separately and the guard doesn't prevent inclusion into multiple TU.

If a header contains definitions that may not be included into more than one TU (such as definition of a non-inline function), then the header is not generally very useful (although, a practical example of this exists: some header-only libraries provide a way to include their own main function definition).

eerorika
  • 232,697
  • 12
  • 197
  • 326
-1

How would the preprocessor know that ignoring it is the right thing to do? For example, consider the following header file, "foobar.h":

FOO(BAR);

And the following C code:

 int main()
 {
#define FOO printf
#define BAR "hello"
#include "foobar.h"
#undef BAR
#define BAR " world\n"
#include "foobar.h"
 }

Here, ignoring the second attempt to include the file would break the program's behavior.

So, since the compiler can't know that ignoring it is the right thing to do, it can't ignore it. So if you want it to ignore it, you'll have to tell it.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278