Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are redundant include guards necessary?

Are 'redundant include guards' necessary in Codegear RAD Studio 2009? Is the compiler smart enough to deal with this on it's own?

For example, I might have the following 'include guard' in foo.h:

#ifndef fooH
#define fooH
// ... declaration here
#endif

and the following 'redundant include guard' in use_foo.h:

#ifndef fooH
    #include "foo.h"
#endif

Additionally, if the compiler is not smart enough, are 'redundant include guards' necesarry if they are being included in a source file. e.g. use_foo.cpp. ?

like image 925
Seth Avatar asked Feb 09 '10 23:02

Seth


People also ask

Should I always use include guards?

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.

Why use #pragma once instead of include guard?

In the absence of #include guards around #include directives, the use of #pragma once will improve compilation speed for some compilers since it is a higher-level mechanism; the compiler itself can compare filenames or inodes without having to invoke the C preprocessor to scan the header for #ifndef and #endif .

Why are header guards needed?

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.

Is pragma once necessary?

We recommend the #pragma once directive for new code because it doesn't pollute the global namespace with a preprocessor symbol. It requires less typing, it's less distracting, and it can't cause symbol collisions.


1 Answers

The portion of the code you marked as "redundant include guard" is not necessary but it is a possible optimization.

In the case of C++Builder, there is logic to detect header guards, so it should not be necessary.

In the general case, the preprocessing pass is usually pretty fast anyhow, so it's unlikely that this optimisation would buy you much anyhow.

like image 142
David Dean Avatar answered Oct 14 '22 23:10

David Dean