Reputation: 11
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)
Upvotes: 1
Views: 174
Reputation: 238461
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).
Upvotes: 2
Reputation: 182865
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.
Upvotes: -1
Reputation: 58929
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.
Upvotes: 3