Sutters guidelines and redundant include guards

I have just come across the guideline: "Always write internal #include
guards. Never write external #include guards." and I have a few
comments about it:

1. Sutter's example is not quite correct. The code fragment he gives is
for headers that do not have a predictable guard (e.g system headers or
third-party headers). When the guard is predictable the construct is
(slightly) smaller, e.g:

#ifndef INCLUDED_FOOBAR_H
#include "foobar.h"
#endif

2. Microsoft compilers and other compilers aimed at Windoze machines do
indeed make redundant include guards, er, redundant. However, Unix
compilers have a long way to go before they catch up in this area.
There maybe perhaps could still be some benefit from using them for
code that has to compile on Unix.

3. IMO the predictable aspect of the include guard has been glossed
over, leaving the impression that the redundant guard construct is
high-maintainance. Well it would be if the guard was not predictable.
But it is predictable, using whatever rules are established in the
corporate coding stds. This reduces the maintainance costs and leaves
one with what is probably the main objection: the code is longer and
more ugly. This is still an understandable reason for avoiding them but
is less strong than Sutter's guideline suggests.

4. Given the above, whether to use them or not boils down to whether or
not the improved builds times is a gain that is worth the cost of the
code uglification. This would have to be measured. Given the
predictable mechanical nature of the redundant guards surely there must
be a tool by now that would convert to use redundant guards, then we
could measure the improvement. So the guideline seems to come down a
little heavy on a measure that could have some benefit.
Regards,

Andrew Marlow


      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]
0
apm35 (156)
12/14/2004 7:54:23 PM
comp.lang.c++.moderated 10720 articles. 0 followers. allnor (8507) is leader. Post Follow

7 Replies
487 Views

Similar Articles

[PageSpeed] 32

apm35@student.open.ac.uk wrote:
> 1. Sutter's example is not quite correct. The code fragment he
> gives is for headers that do not have a predictable guard (e.g
> system headers or third-party headers). When the guard is
> predictable the construct is (slightly) smaller, e.g:
>
> #ifndef INCLUDED_FOOBAR_H
> #include "foobar.h"
> #endif

Why would you need to write the external guard, though? Maybe you
weren't aware of the optimizations done by UNIX compilers?

> 2. Microsoft compilers and other compilers aimed at Windoze
> machines do indeed make redundant include guards, er, redundant.
> However, Unix compilers have a long way to go before they catch
> up in this area. There maybe perhaps could still be some benefit
> from using them for code that has to compile on Unix.

Unfortunately, #pragma once is not standard, and it's not just an
optimization. Often, including multiple times generates wrong code,
like violating the ODR. You still need the redundant include guards for
portable code.

Most UNIX compilers have their own optimization, instead of #pragma
once, and it is better. They recognize the structure of a redundant
include guard, and will not read the file multiple times, as they
understand it's a no-op. This fails gracefully on compilers that don't
support the optimization.

However, Windows compilers tend not to support the optimization, so
there is a lot of code like this,

#ifndef SOMEFILE_H
#define SOMEFILE_H
#ifndef LACKS_PRAGMA_ONCE
#pragma once
#endif // !LACKS_PRAGMA_ONCE
// ...
#endif // !SOMEFILE_H

I believe ACE starts every hearder with a construct like that. It does
work though, and it should eliminate any motive for external include
guards unless you're using a terribly dated compiler.

-- 
Dave O'Hearn


      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]
0
Dave
12/15/2004 4:44:07 AM
apm35@student.open.ac.uk wrote:
> I have just come across the guideline: "Always write internal #include
> guards. Never write external #include guards." and I have a few
> comments about it:
> 
> 1. Sutter's example is not quite correct. The code fragment he gives is
> for headers that do not have a predictable guard (e.g system headers or
> third-party headers). When the guard is predictable the construct is
> (slightly) smaller, e.g:
> 
> #ifndef INCLUDED_FOOBAR_H
> #include "foobar.h"
> #endif
> 
> 2. Microsoft compilers and other compilers aimed at Windoze machines do
> indeed make redundant include guards, er, redundant.

Assuming you don't include the a header file through two different
paths that it doesn't realise are the same - though that would be
rather silly.

> However, Unix compilers have a long way to go before they catch up
> in this area.
<snip>

GCC's preprocessor recognises the ifndef...#define...#endif pattern
#and can skip the whole file if it's included again.  Any other
implementer is free to do the same.  There's no need for a
non-standard extension, or the external guards.  This also avoids the
problem of having to know for certain whether two paths point to the
same file.

-- 
Ben Hutchings
compatible: Gracefully accepts erroneous data from any source

      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]
0
Ben
12/15/2004 4:45:34 AM
I know that not every platform supports #pragma once. But does anybody
know of a platform where it does something undesirable?

IMO, warnings would count as undesirable if there was no easy way to
supress them. But according to the standard (16.6):
Any pragma that is not recognized by the implementation is ignored.


      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]
0
Allan
12/15/2004 6:16:26 PM
Ben Hutchings wrote:

> GCC's preprocessor recognises the ifndef...#define...#endif pattern
> #and can skip the whole file if it's included again.  Any other
> implementer is free to do the same.  There's no need for a
> non-standard extension, or the external guards.  This also avoids the
> problem of having to know for certain whether two paths point to the
> same file.

It's worth noting that GCC has done this for quite some time now, at
least ten years.  It's surprising that so few other compilers have
adopted the technique.

--
James Kanze           GABI Software         http://www.gabi-soft.fr
Conseils en informatique orient�e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S�mard, 78210 St.-Cyr-l'�cole, France, +33 (0)1 30 23 00 34


      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]
0
kanze
12/15/2004 6:17:10 PM
Allan W wrote:
> I know that not every platform supports #pragma once. But does
> anybody know of a platform where it does something undesirable?
>
> IMO, warnings would count as undesirable if there was no easy
> way to supress them. But according to the standard (16.6):
> Any pragma that is not recognized by the implementation is
> ignored.

I put it in the !LACKS_PRAGMA_ONCE test because older versions of gcc
issue a warning that "`#pragma once' is obsolete". It's annoying, and I
don't know how to disable it. gcc 3.4 has correct support for pragma
once and doesn't issue the warning.

Both gcc and MSVC++ issue warnings on unrecognized pragmas, but they
both have ways to disable them. In general though, I just find pragmas
scary, and I like to #ifdef them.

-- 
Dave O'Hearn


      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]
0
Dave
12/16/2004 1:20:47 PM
Dave O'Hearn wrote:
> including multiple times generates wrong code,
> like violating the ODR. You still need the redundant include guards
for
> portable code.

I think you are confusing redundant include guards with conventional
include guards. Conventional include guards are used to protect againts
harmful results if a file is included multiple times in a TU. This is
done by the file beginning with #ifndef guardname #define guardname
blah-blah #endif. This protects against ODR etc. Redundant include
guards are an ADDITIONAL measure where the include guard macro is
tested to ensure that the #include is not performed if the inclusion
has already been made.

With conventional include guards the header may be parsed many times
but each time other than the first is effectively a no-op. However, the
use of conventional include guards without the additional measure of
redundant include guards means that extra work is done in finding and
opening the file and parsing its contents (albeit the contents will be
quickly scanned until the closing #endif is encountered).

>
> Most UNIX compilers have their own optimization, instead of #pragma
> once, and it is better. They recognize the structure of a redundant
> include guard,

They recognise the construct of a *conventional* include guard. And so
the cost of finding and opening the file (which is large compared to
the cost of skipping to the closing #endif) is still incurred.

> work though, and it should eliminate any motive for external include
> guards unless you're using a terribly dated compiler.

One of my points was that commercial unix compilers are not exactly
leading edge and so do not (AFAIK) have any work done in this area.
-Andrew M.


      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]
0
apm35
12/16/2004 1:32:15 PM
apm35@student.open.ac.uk wrote:
> Dave O'Hearn wrote:
>> including multiple times generates wrong code,
>> like violating the ODR. You still need the redundant include guards
>> for portable code.
<snip> 
> With conventional include guards the header may be parsed many times
> but each time other than the first is effectively a no-op. However, the
> use of conventional include guards without the additional measure of
> redundant include guards means that extra work is done in finding and
> opening the file and parsing its contents (albeit the contents will be
> quickly scanned until the closing #endif is encountered).
<snip>

A smart preprocessor can identify the guard macro the first time a
file is included and check it the second time before opening the file.
(It is reasonable to assume that source files are not modified during
compilation.)  This is what GCC's preprocessor does. See
<http://gcc.gnu.org/cgi-bin/cvsweb.cgi/gcc/libcpp/files.c?rev=1.1.2.3>
and in particular the function should_stack_file.

-- 
Ben Hutchings
This sentence contradicts itself - no actually it doesn't.

      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]
0
Ben
12/17/2004 4:40:47 AM
Reply:

Similar Artilces:

C/C++ guidelines
Hi groups, I'm about to embark on a new project and for maximum portability we've been asked to code it in the common subset of C and C++. Can anyone suggest any good documents that might help us? Lists of gotchas to avoid, that sort of thing? TIA! Robbie Robbie Marshall wrote: > Hi groups, > > I'm about to embark on a new project and for maximum portability we've > been asked to code it in the common subset of C and C++. > For maximum portability, code in C89. If you aren't aware of the (sometimes subtle) differences between C and C++ (even within t...

Testing C include file for C++ compatibility without a C++ caller?
I have a C package that until recently was callable by C++ programs without generating warnings. Everything is properly wrapped up in #ifdef __cplusplus extern "C" { #endif which I always assumed precluded the possibility of a cleanly compiling C module throwing warnings and errors when compiled by a C++ compiler. However, recent versions of g++ throw warnings like this when some C++ modules include AND use one of the include files in the package: .../../src/extension/internal/metafile-print.cpp:132:13: warning: narrowing conversion of ‘((color >> 16) &...

Comments outside include guards (from a Sutter/Alexandrescu advice)
Hi, after several "tweaks" I think I've finally found a file layout which I like for my code (in terms of where the copyright line and the license reference go, where the vim modeline etc.). For included files, I've stuck so far to the suggestion in C++ Coding Standards which says: Don't try to be clever: Don't put any code or comments before and after the guarded portion, and stick to the standard form as shown. Today's preprocessors can detect include guards, but they might have limited intelligence and expect the guard code to appear exact...

c++ non-lang tuts, but on linking, libraries, workspaces and includes
I keep digging through tut after tut and I find lots and lots of C++ logic, but I can't find any straight forward plain and simple info on the whole linking and library process. Can anyone recommend a good source to digest that covers what is going on in this regard? I can get things to work with the 'monkey see' technique but it is still all voodoo. I need to understand things like, how make files work, how vc++6 project files work, include paths, lib paths, dll linking stuff and all that. I really want to know why it works, not just how to drop in directory paths to stop stuf...

Better C/C++ Than C/C++?
I am looking for a good systems programming language that can be used instead of C/C++. My qualifications for the language are: * mature compiler(s) that produce native-code binaries (for Windows) * open source - preferable, but not 100% necessary Thanks, Kevin "Kevin Albrecht" <kevin@albrecht.net> writes: > I am looking for a good systems programming language > that can be used instead of C/C++. My qualifications > for the language are: > > * mature compiler(s) that produce native-code > binaries (for Windows) Ocaml, D, cyclone, Eiffel, Beta >...

jython and C-c C-c
How do I get C-c C-c to work with jython? I have the jpython command set to jython, and I can start the interpreter with C-C ! and then use C-c C-c, but this is rather frustrating. If I try to use C-c C-c without first starting the interpreter in another window I get wrong type argument: sequencep, jpython Thanks, Dave Cook ...

Consider using redundant include guards to improve ACE compile time
I just thought I would offer a suggestion that I believe would significantly improve compile times for ACE/TAO/CIAO. Putting redundant include guards in the header files reduces compile time by eliminating the need for the preprocessor to read header files that have already been included elsewhere. For example, Thread_Manager.h includes Thread.h as do a number of other files. Each time the preprocessor encounters an include for Thread.h it has to go out to disk and open the file only to discover the include guard inside Thread.h. It then reads to the end of the #ifndef section and su...

Including external Libaries (C/C++)
Hello, which Smalltalk product is best for integrating C/C++ libraries in the Smalltalk enviroment of the vendor? I'm looking for a Smalltalk that has a good C/C++ API glue. Is it possible at all? Platform would be Windows. The C/C++ library I want to integrate has realtime Events coming from financial markets (C/C++ callbacks) that need to be processed and displayed in a GUI (stock price ticker for example). My Smalltalk backround is 10 years back (Enfin Smalltalk). I don't know if this product exists any more and what is state of the art at the moment. So I need ...

including c libs in c++ code?
Hi I am trying to compile a cpp ap that runs on the system tray and checks recently open files with clamav. i am getting a whole bunch of undefined erros. can i link this library to a cpp program? do i need any special confiure options?. i tried removing pthread and other libraries and the results are similar. or should i write a small lib that checks buffers and just use my lib with extern? thanks for the advice. the code looks like this extern "C" { #include "clamav.h" int cl_loaddbdir(const char *dirname, struct cl_node **root, int *virnum); } compiled with redi...

how to include a c struct in C++ namespace
Hi, I am trying to wrap c functions with some exception handling, for example, wrap the socket bind in A::Bind a.h namespace A { int Bind(int fd, struct sockaddr *addr, socklen_t addrlen) throw (inet_error); } a.cc namespace A { int Bind(int fd, struct sockaddr *addr, socklen_t addrlen) throw (inet_error) { /* if error, throw; otherwise return; */ } } The problem is this generates link error, error: reference to =91sockaddr=92 is ambiguous.... it seems the compiler think I define a new struct, with the same name "sockaddr" in name space A, I tr ied to remove the struct ...

security coding guidelines for C/C++
I am Aravind.Could someone provide me with a list of specific guidelines for secure programming in C/C++?.I would like to use those guidelines for developing a security application to deal with issues like buffer overflows,memory leaks,user input validation etc.... Aravind Aravind wrote: > > I am Aravind.Could someone provide me with a list of specific > guidelines for secure programming in C/C++?.I would like to use those > guidelines for developing a security application to deal with issues > like buffer overflows,memory leaks,user input validation etc.... No. Nobody here ...

[9fans] Include guards and multiple includes
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 I'm trying to convince some non-believers that include files should not include other include files, and that instead they should state their dependencies; they want hard data before they commit to such a scheme. Is there some study kicking around that I could point them at rather than re-factor our code base and time the resulting builds? I know the plan9 headers largely follow this pattern. Paul -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.3 (Darwin) iD8DBQFFORlRpJeHo/Fbu1wRAlExAKCsTZtCcW9FlqvUwllBye9EgRGqGwCgnYZn 0QcMNw3...

dialect of c++ that includes ansi C
Hi all, I use a c++ front end to compile C code, I run into problems when void* pointers are implicitly converted. Is there a fix to this kind of issue? Are there c++ dialects that are supersets of C? thanks in advance, vlad vcciubot@gmail.com wrote: > I use a c++ front end to compile C code, I run into problems when > void* pointers are implicitly converted. Is there a fix to this kind > of issue? One can write C code that is also "C-style" C++ code. This requires avoiding C's known abuses, such as converting from void* too easily, and requires adding C-style typ...

Intelligent include-guard processing (C++ Coding Standards, Items 23 & 24)
Item 24 says we shouldn't place any comments before an include guard. This could apparently prevent compilers from using intelligence as mentioned in Item 23: "Many modern C++ compilers recognize header guards automatically ... and don't even open the same header twice". I suppose I should do some tests for myself to see how significantly the effect can be demonstrated on the compilers in use at work, but before I go to that effort can anyone tell me which compilers this applies to, or doesn't apply to? (My current code base almost universally has copyright etc co...

Web resources about - Sutters guidelines and redundant include guards - comp.lang.c++.moderated

Debian Free Software Guidelines - Wikipedia, the free encyclopedia
In November 1998, Ian Jackson and others proposed several changes in a draft versioned 1.4, but the changes were never made official. Jackson ...

Wikipedia:Non-free use rationale guideline - Wikipedia, the free encyclopedia
This page documents an English Wikipedia content guideline . It is a generally accepted standard that editors should attempt to follow, though ...

ShortStack Responds To Facebook’s Revamped Promotions Guidelines With Comment/Like Importer
Facebook application creator ShortStack reacted to Facebook’s announcement Tuesday that third-party apps are no longer required to create promotions ...

Guidelines released for mandatory LGBTQ policies in Alberta schools
... to self-identify their gender and be addressed by the name and pronoun of their choice. School boards across Alberta have been given guidelines ...

Bishop Fred Henry Says Alberta's New LGBTQ School Guidelines Are 'Anti-Catholic' 211
The rules would protect LGBTQ students from discrimination in school.

The 2015-2020 Dietary Guidelines: What Marketers Should Know
The 2015-2020 Dietary Guidelines for Americans, released Thursday, suggest that American diets could use a little work. Overall, the main ideas ...

UK tightens drinking guidelines—no more than 6 beers a week
... have updated their recommendations for alcohol consumption—and it’s likely the new rules won’t sit well with many Britons. The tougher guidelines ...

The CDC just released new guidelines about the fast-spreading Zika virus
... a serious birth defect. Now, after a baby born with brain abnormality in Hawaii tested positive for the virus, the CDC has come up with guidelines ...

Dietary Guidelines: What do they mean for marketers?
Every five years, the U.S. Department of Health and Human Services (HHS) releases Dietary Guidelines for Americans—they’re supposed to be a resource ...

New guidelines recommend mammograms begin at age 50 - Videos - CBS News
A government medical panel put out new guidelines for when and how often women should be screened for breast cancer, but they are sparking debate ...

Resources last updated: 1/24/2016 3:17:46 PM