Valid uses for C++ include guards besides, well, include-guarding? - c++

This question is one of several that discuss naming conventions for C++ include guards. The person asking that question thinks that this naming convention:
#ifndef FOO_H
#define FOO_H
// ...
#endif
is a bit non-intuitive when taken by itself (what does FOO_H mean?) and I tend to agree.
Others say that, barring the need to add more stuff for better collision avoidance (like PROJECTNAME_FOO_H_SDFFGH69876GF), the name FOO_H is just fine because it's clear from its context what its purpose is (namely, it's at the beginning of the files of the same name and it's clear that it's an include guard).
I could buy this if the only purpose of having FOO_H would be to guard against multiple inclusion, but are there conditions for which I'd want to have FOO_H elsewhere in the files? I'd think conditional compilation would be a good reason, in which case naming it something like FOO_H_INCLUDED would be clearer.
Are there straightfoward uses akin to this, or should I avoid repurposing the include guards?

I think the question is flawed in itself. The term include guards refers to #defines and checks for #defined in the particular use of guarding against multiple inclusion, which is as much to say that is the only use for that.
Now taken a little more generally, defines and conditional compilation can be used for other things, like writing bits of code that are platform dependent and will only get compiled under some circumstances...
Whether FOO_H or FOO_H_INCLUDED is better, I will always say that the later is the most expressive, and then I will go back to vi and type FOO_H in my next foo.h header. Again, as I mentioned in a comment on the other question, you grow used to the pattern:
#ifndef XXXXXXXXX
#define XXXXXXXXX
#endif
as the first two and last line in a file and you end noticing. That is until it bites back if you have reused the same name...

Sometimes, I use this for "implementation" header files. Actual naming scheme for guards may differ.
#ifndef FOO_IMPL_H
#define FOO_IMPL_H
#ifndef FOO_H
#error Don't include this directly
#endif
// Ugly implementation of the stuff in foo.h, with an uncountable
// number of template and typename keywords
#endif

In my opinion, include guards should be include guards and nothing more. If you want conditional compilation, I would define something else. If you were throwing around #if defined(FOO_H) in your code, I think people would find this strange since _H usually indicates an include guard.
One thing I can think of though is checking if the file has already been included (duh!) so that you don't have to include the file yourself. I'm not sure if this would speed up compilation or not, in comparison to forward declarations or #pragma once
In main.cpp:
#include "bar.h" // comment this line to see the difference
#include "foo.h"
int main()
{
return 0;
}
In bar.h:
#ifndef BAR_H
#define BAR_H
class BarClass
{
};
#endif
In foo.h:
#ifndef FOO_H
#define FOO_H
#if !defined(BAR_H)
#error bar h was not included // forgot how to do compiler warnings...
#include "bar.h" // we should include the file
#else
#error bar h was included // same thing, should be changed to warning
#endif
// do something with BarClass
#endif FOO_H

I'd think conditional compilation would be a good reason, in which case naming it something like FOO_H_INCLUDED would be clearer.
I only see one very narrow use here to avoid including a header when you only need a forward declaration, but want to skip the forward declarations if the header has previously been included.
However, this is not a bottleneck in compiling C++ today, and the added confusion over either always having the forward declarations or always including the header is not worthwhile.
Even if you needed tons – and I mean hundreds to thousands of lines of these forward declarations – so that it did become worthwhile, you'd be better off with a dedicated header, similar to <iosfwd>, rather than maintaining this in multiple places.

For repurposing: unless the entire contents of the file are surrounded by the ifndef/define/endif, then FOO_H isn't really a file include guard, it's only guarding part of a file. So possibly it shouldn't be named after the whole file. Recursive inclusion of the same file is one situation where this can come up.
That said, I suspect that even so, it should be pretty obvious what the define is for (anyway, more obvious that whatever tricksy thing it is you're doing that isn't simple include guarding). Anywhere you see the pattern ifndef FOO/define FOO, or even just ifndef FOO / define lots of stuff, a simple comment can make the meaning of FOO obvious if it isn't already.
If any part of the question is whether the token FOO_H might ever be used for some other purpose: I guess if you have a file somewhere called uppercase.h which uses UPPERCASE_H as an include guard, then that could conceivably clash with someone's rot13.h, containing #define UPPERCASE_A ('N'), etc. Silly example, but if you were defining properties of letters in a header file then it's not ridiculous to think that some of them might end in _H.
More realistically, I've had projects with include files having the same basename in different directories.
So, regardless of the issue of context and repurposing, I wouldn't use FOO_H as an include guard.

Related

How do I make header files?

I have gotten to a point in my course where they use Code::Blocks to automatically make a header file. However, I don't think it's necessary to download Code::Blocks specifically for this reason, and so I am looking for a way to make my own header files.
And so, I started my search online to find out exactly how to do this.
I checked How to create my own header file in c++? [closed] and also cplusplus.com
However, the former uses uses #ifndef YOUR_NAME_INCLUDE and #define YOUR_NAME_INCLUDE whereas the latter uses #ifndef __X_H_INCLUDED__ and #define __X_H_INCLUDED__, with 2 underscores surrounding the #ifndef and #define. How should I format my header guards? Does it really matter?
For example, if I have a file foo.h, which looks like this:
#ifndef ???
#define ???
int sum(int a, int b) {
return a + b;
}
#endif
should I put SUM_INCLUDED, FOO_INCLUDED, FOO_H instead of the ??? or something else altogether?
Second, is making a header file really as easy as just sticking a .h or .hpp to the end of it?
#ifndef FOO
#define FOO
struct foo {};
#endif
The above canonical example ensures that the contents (between #ifndef FOO and #define FOO) are compiled only once allowing us to include this file (say foo.h) in multiple compilation units without causing struct foo to be multiply defined.
There really isn't any "magic" about an include file other than this. In fact, the extension doesn't even matter. It could be foo.h or foo.hh or just foo (like the standard library headers like vector or iostream).
Ultimately, it's personal preference how you structure your include guards. Some use __FOO__ (note this runs afoul of C++ standard regarding reserved identifiers) or FOO_H_INCLUDED (which is standard compliant) while others may elect for different patterns.
While it's not strictly standard C++, my team uses #pragma once and foregoes the ifndef/define/endif code. It's supported by all the compilers we use (gcc/msvc/clang) and you don't have drawbacks such as too different foo.h files causing one (or the other) definition to be excluded.
The same file then looks like this
#pragma once
struct foo {};

Can/should I type whatever I want after #ifndef?

Example:
#ifndef HEADER_h
#define HEADER_h
#endif
Instead of HEADER_h, can I do the following?
#ifndef HEADER
or
#ifndef LIBRARY
or
#ifndef SOMETHING
or
#ifndef ANOTHERTHING
etc.
Header guards are just a convention, a "trick", making use of preprocessor conditions. In using a header guard you are creating a macro with a name, and checking whether that macro was already defined.
There is nothing magical about this macro that binds it to the filename of a header, and as such you can call it whatever you want (within reason).
That doesn't mean that you should write #ifndef URGLEBURGLE, though. You want the name to be useful and unique, otherwise there's not much point.
Typically something like #ifndef [PROJECTNAME]_[FILENAME]_INCLUDED is a good idea.
Yes, you can name the include guard symbol whatever you want, but bear in mind that they are supposed to be unique across headers. You definitely don't want a header
// first.h
#ifndef NON_UNIQUE_H
#define NON_UNIQUE_H
void foo();
#endif
and another one
// second.h
#ifndef NON_UNIQUE_H
#define NON_UNIQUE_H
void bar();
#endif
When you include both in one translation unit, one will "win" and its declarations will be visible, e.g.
// main.cpp
#include "first.h" // now, NON_UNIQUE_H is defined
#include "second.h" // NON_UNIQUE_H already there, doesn't do anything
int main(int, char**)
{
bar(); // error, won't compile, bar() isn't declared
}
Besides the necessity to circumvent such scenarios, it's best to stick to some convention throughout your project. One classical way of doing it is to convert the header file base name to upper case and append _H. If you have header files with the same base name in different directories, you can include the directory name, e.g. SUBDIR_FOO_H and OTHERSUBDIR_FOO_H. But this is up to you.
You can use a construction like
#if !defined(HEADER) || !defined(LIBRARY)
At your question, you are using
#ifndef HEADER_h
#define HEADER_h
#endif
It's the same as "#pragma once"
And yes, you can use different names of defines. In your case, LIBRARY, SOMETHING, HEADER_h - defines, that you can set in code(#define MY_VAR_NAME) or via compiler options(flag -DMY_VAR_NAME).
Your example is a so-called header guard that allows us to ensure the contents of the header are included only once. However, that is not the only use of #ifndef.You can use #ifndef for conditional compilation as in
#ifndef NO_DEBUG
do_some_debug_stuff();
#endif
So it is not only for header guards, but in general you have to carefully choose the name of the symbols you are introducing to prevent they are clashing with symbols defined elsewhere. It is just that header guards are so common that certain conventions exist (eg using FOLDER_FILENAME_H is usually sufficient to ensure uniqueness). And you need to be aware that certain names are reserved (eg starting with two underscores or underscore followed by capital letter).

#ifndef syntax for include guards in C++

I'm currently studying for a CS course's final exam and I've run into a minor (maybe major?) issue regarding the syntax of C++ #ifndef.
I've looked at the syntax for #infndef when using it as an #include guard, and most on the web seem to say:
#ifndef HEADER_H
#define "header.h"
...
#endif
But my class's tutorial slides show examples as:
#ifndef __HEADER_H__
#define "header.h"
...
#endif
I was wondering what (if any) the difference was between the two. The exam will most likely ask me to write an #include guard, and I know conventional wisdom is to just go with what the prof / tutor says, but if there's a difference during compilation I'd like to know.
The usual practice is to do neither, and put the include guard inside the header file, as it reduces repetition. e.g.:
header.h
#ifndef HEADER_H
#define HEADER_H
// Rest of header file contents go here
#endif
Precisely what you use as the macro name is down to your particular coding standard. However, there are various subtle rules in the C and C++ standards that prevent you from using identifiers beginning with underscores,1 so you should avoid __HEADER_H__, just to be on the safe side.
It's also worth mentioning that you should pick something that's unlikely to clash with anything else in your codebase. For example, if you happened to have a variable called HEADER_H elsewhere (unlikely, I realise), then you'd end up with some infuriating errors.
1. See e.g. section 7.1.3 of the C99 standard.
Names starting with a double underscore are reserved for the implementation, so I would advise against using __SOMETHING in your include guards. Also, try to chose names that make clashes unlikely. So it seems your class' tutorials are wrong on at least two counts. See this humorous article for example.
An argument for putting the include guards in the file that includes the header, rather than in the header itself, is that if the file has already been included the compiler (specifically the preprocessor) doesn't have to open and read the include file again.
That's a weak argument. In practice, the time saved is trivial, and the potential for error is large.
In your example:
#ifndef HEADER_H
#include "header.h"
...
#endif
you don't show us the #define HEADER_H. Is it somewhere in header.h? If so, how do you know that the author of header.h chose to use HEADER_H as the name of the include guard macro? What if it changes to something else later?
If you decide to put the include guard in the including file, you should define the macro there as well:
#ifndef HEADER_H
#include "header.h"
#define HEADER_H
#endif
But, as other answers have already said, it's much better to put the guard in the header itself:
header.h :
#ifndef HEADER_H
#define HEADER_H
/* contents of header.h */
#endif
and then the include simply has:
#include "header.h"
and has one less piece of information to worry about.
There's no difference if you don't use underscore in variable names anywhere else, it's only a naming convention.
You just need to put something unique.

Undefine already included header

I want to check a header in my source file and if its already defined, I want to undefine it.
Is it possible?
#undef is the opposite of #define and actually cancels it.
It's very useful when you need a macro for some task but does not wish to "pollute" the symbol tables
// referencing FOO is an error (not yet defined)
#define FOO(arg_) ....
FOO(A)
FOO(B)
FOO(C)
#undef FOO
// referencing FOO now is an error (not defined)
There is no way to cancel a #include directive.
'including' something in c/c++ essentially means: make the preprocessor copy and paste the #include <file> directly into your source code (or better: the preprocessed version of your source code).
you can not make that copy and paste action undone. you can however '#undef' stuff introduced by that copy and paste action, but you have to do this for every atom you dislike, you just can't #undef the whole file.
to check, if a given header was already included, you have check if something from that header file is defined already. most headers contain so called 'guards' which look like
#ifndef FOO_H
#define FOO_H
/* lots of code */
#endif
for a file called 'foo.h'. you could check for 'FOO_H' like this:
#ifdef FOO_H
/* do your magic */
#endif
example:
foo.h:
#ifndef FOO_H
#define FOO_H
struct Foo { /* ... * };
#endif
bar.h:
#include "foo.h"
#ifdef FOO_H
#undef Foo
#endif
but that can lead to a lot of headaches if you are not aware of what exactly you are doing. IF your real problem is, that your compiler complaints about 'already declared stuff' then you are not guarding your header files against multiple inclusion...
Do you mean you want to ensure that the header file is included once and only once? The standard solution to this is using an include guard.
I.e. surround the contents of your header with
#ifndef MY_HEADER // a unique identifier for each header
#define MY_HEADER
...
#endif
This is guaranteed to work in all platforms. Some compilers also provide a #pragma to achieve the same effect with less hassle, e.g. in Visual C++ you can add
#pragma once
at the start of your header file.
You can't do what you seem to want to do. If you don't want the header included your choices are
don't include it in the first place
conditionally include it or not via the prepocessor e.g.
#ifdef INC_MY_HEADER
#include "myheader.h"
#endif
or assuming the header has header guards just define the header guard before the header is included e.g. from the commend line -DMY_HEADER or similar
If the real problem is that you have different headers defining things with the same name then you probably need to look into namespaces so you don't get clashes
You could stop the header being included - the simplest way would be to remove or comment out the #include directive.
You could also pre-define your guards so that the include is inneffective.
foo.h
#ifndef __FOO_H
#define __FOO_H
/* contents of foo.h */
#endif /* __FOO_H */
foo.cpp
#define __FOO_H
#include "foo.h"
/* contents of foo.cpp */
Using this strategy you could use the preprocessor to select whether to pre-define the guards, or even have inner guards within you header.
If you really need only to have part of the file included, it would be better to split the file into two.

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. ?
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.
These redundant include guards are intended to emulate the functionality of the proposed #pragma once directive: if some header file has already been included, then the preprocessor will not even attempt to locate, open and parse it anymore (as it would have to with the "ordinary" include guard technique). In many cases this makes handling of include files much more efficient (speeds up compilation).
This approach is obviously a high-maintenance one: one has to make sure that the spelling of the guard symbol is exactly the same inside the header file as well as outside.
The "redundant include guard", as you call it, speeds up compilation.
Without the redundant guard, the compiler will iterate the entire foo.h file, looking for some code that might be outside the #ifndef block. If it's a long file, and this is done many places, the compiler might waste a lot of time. But with the redundant guard, it can skip the entire #include statement and not even reopen that file.
Of course, you'd have to experiment and see the actual amount of time wasted by the compiler iterating through foo.h and not actually compiling anything; and perhaps modern compilers actually look for this pattern and automatically know not to bother opening the file at all, I don't know.
(Begin edit by 280Z28)
The following header structure is recognized by at least GCC and MSVC. Using this pattern negates virtually all benefits you could gain with guards in the including files. Note that comments are ignored when the compiler examines the structure.
// GCC will recognize this structure and not reopen the file
#ifndef SOMEHEADER_H_INCLUDED
#define SOMEHEADER_H_INCLUDED
// Visual C++ uses #pragma once to mark headers that shouldn't be reopened
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
# pragma once
#endif
// header text goes here.
#endif
(End edit)