Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Including header files in C/C++ more than once [duplicate]

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?

like image 351
math4tots Avatar asked Jun 04 '12 07:06

math4tots


People also ask

What happens if we include a header file twice in C?

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.

How can you avoid including a header more than once in C?

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.

Can you have multiple header files in C?

Including Multiple Header Files:You can use various header files in a program.

Can we use same header files in multiple C programs are not?

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.


1 Answers

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.

like image 135
Pubby Avatar answered Sep 18 '22 03:09

Pubby