Is it ever useful to include a header file more than once in C or C++?
If the mechanism is never used, why would the compiler ever worry about including a file twice; if it really were useless, wouldn't it be more convenient if newer compilers made sure every header is included only once?
Edit:
I understand that there are standard ways of doing things like include guards and pragma once, but why should you have to specify even that? Shouldn't it be the default behavior of the compiler to include files only once?
If a header file happens to be included twice, the compiler will process its contents twice. This is very likely to cause an error, e.g. when the compiler sees the same structure definition twice. Even if it does not, it will certainly waste time. This construct is commonly known as a wrapper #ifndef.
To avoid multiple inclusions of the same header file we use the #ifndef, #define and #endif preprocessor directives. Just write the entire program in only file and include headers once only. You can use the conditional preprocessor directive named #ifndef to check whether that symbolic name has already been assigned.
Including Multiple Header Files:You can use various header files in a program.
Summing up: it is not redundant to include the same files in different C files -- it is formally required. (Afterwards, you link object files, which are just smaller programs, into a larger final program.
Yes, it's useful when generating code with the preprocessor, or doing tricks like Boost.PP does.
For an example, see X Macros. The basic idea is that the file contains the body of the macro and you #define
the arguments and then #include
it. Here's a contrived example:
macro.xpp
std::cout << MESSAGE; #undef MESSAGE
file.cpp:
int main() { # define MESSAGE "hello world" # include "macro.xpp" }
This also allows you to use #if
and friends on the arguments, something that normal macros can't do.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With