Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When not to use include guard in header file?

We all know when to use include guard, but when shall we not use it in our project?

Recently, I saw a project with mix compilation (CUDA + GCC), one header file (CUDA file) is deliberately left without include guard. I am just curious about it.

like image 843
Lonelydove Avatar asked Jul 22 '11 16:07

Lonelydove


People also ask

Is include guard necessary?

Formally, you don't need include guards in your bar. h . It has a single function declaration, which can be repeated many times in one translation units. So, including this header multiple times will not lead to errors.

How important is it to have an include guard for every header file?

Header guards are designed to ensure that the contents of a given header file are not copied, more than once, into any single file to prevent duplicate definitions. This is a good thing because we often need to reference the contents of a given header from different project files.

What problem can occur when a C++ header file lacks include guards?

These user-defined types are typically defined in header files, so the type definitions can be propagated out to the code files that need to use them. Without a header guard, a code file could end up with multiple (identical) copies of a given type definition, which the compiler will flag as an error.

Should you include in header files?

Such project header files should contain #include statements for the system headers; if the body includes them first, the compiler does not check this.


2 Answers

There are 2 scenarios off the top of my head:

  1. when you want to turn on/off debugging capabilities (as how assert.h works)
  2. for 'x-macro' type of functionality where you have the include file perform 2 parts of problem, such as defining an enum then defining an array of stringified names corresponding to the enums
like image 182
Michael Burr Avatar answered Sep 21 '22 05:09

Michael Burr


One case in when you do want to include the same file several times with different parameters. In this case the include file would act as a sort of template. An example are the scalers on Dosbox.

like image 43
ninjalj Avatar answered Sep 19 '22 05:09

ninjalj