3 ms·
Includes predate C++ by a bit. And there is nothing that specifically forbids such a thing; it's just the preprocessor literally inserting (and interpreting) th
by ygra 13y ago
Includes predate C++ by a bit. And there is nothing that specifically forbids such a thing; it's just the preprocessor literally inserting (and interpreting) the file specified.
Now, normally there are include guards (or #pragma once) to guard against including the same header file twice. But of course that's only necessary because the language specification doesn't say that including the same file twice is disallowed.
One can surely construct something where including the same file twice does make sense, e.g. in the light of new #defines in between the two inclusions:
// foo.h
#ifdef FOO
...
#else
...
#endif
// foo.c
#include "foo.h"
#define FOO
#include "foo.h"
Mind you, this is probably not a good idea, at all. But some people might build such things. A similar method that springs to mind is Android's native build system ndk-build, which is a thickly-veiled GNU make where you basically include targets that do something with a lot of variables you set beforehand. And you can do so multiple times in a row. Maybe the included file uses a defined symbol to emit some generated code based on that symbol and you might want to do that with several symbols. Macros are usually preferred for that, but nothing stops you from using an included file.
- pavanky 13y agoAlso do not forget the more common case: - foo.c includes bar.h and baz.h - bar.h and baz.h both include qux.h This is why most C header files have ifdef guards like this #ifndef __BAR_H #define __BAR_H // contents go here #endif This makes sure that the contents of the header are only included the first time the preprocessor sees it in a particular file
- ygra 13y agoHence include guards, yes. Agreed, I could have made that point a little better. Although they are usually only necessary when the header files contains things that may not appear twice in the same compilation unit, such as ... uhm, pretty much everything.