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.
Related
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).
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.
while I am creating a c++ header file, I declare the header file like;
/*--- Pencere.h ---*/
#ifndef PENCERE_H
#define PENCERE_H
I want to learn that why do I need to write underline.
You don't need to use the underline, it's just a convention to separate the header name and extension. You cannot use the literal . since that's not valid in an identifier so you replace it with an underscore which is valid.
The reason you actually do it is as an include guard. The entire contents of the file are something like:
#ifndef PENCERE_H
#define PENCERE_H
// Your stuff goes here.
#endif
so that, if you accidentally include it twice:
#include "pencere.h"
#include "pencere.h"
you won't get everything in it duplicated. The double inclusions are normally more subtle than that - for example, you may include pax.h and diablo.h in your code and pax.h also includes diablo.h for its purposes:
main.c:
#include "pax.h"
#include "diablo.h"
// Other stuff
pax.h:
#ifndef PAX_H
#define PAX_H
#include "diablo.h"
// Other stuff
#endif
diablo.h:
#ifndef DIABLO_H
#define DIABLO_H
typedef int mytype;
#endif
In this case, if the include guards weren't there you would try to compile the line typedef int mytype; twice in your program. Once for main.c -> pax.h -> diablo.h and again for main.c -> diablo.h.
With the include guards, the pre-processor symbol DIABLO_H is defined when main.c includes diablo.h so the #define and typedef are not processed.
This particular mapping of header files to #define names breaks down in the situation where you have dir1/pax.h and dir2/pax.h since they would both use PAX_H. In that case, you can use a scheme like DIR1_PAX_H and DIR2_PAX_H to solve the problem.
The underline is not necessary, that's just a way to produce a string for the include guard that is unlikely to be produced anywhere else and cause hard to detect problems. Even more, you are free to select any symbol for the include guard as long as it will not be defined anywhere else.
It's because you can't #define PENCERE.H
You can define anything you want, but by using a format of using the filename, replacing . with _ means you shouldn't clash #defines that guard importing the same header file twice.
You don't need to write the underline. All you need is a preprocessor symbol which isn't defined anywhere else. If you like (and/or if you have a Pascal background ;-}) you could just as well say
/*--- Pencere.h ---*/
#ifndef THE_PENCERE_HEADER_FILE_WAS_INCLUDED
#define THE_PENCERE_HEADER_FILE_WAS_INCLUDED
I'm a bit new to C++, so bear with me. I'm trying to figure out where exactly to place my #defines and #includes in my project. I have something like this:
main.h
#include "other.h"
#define MAX_GROUPS 100
struct Cat
{
int something[MAX_GROUPS];
}
In other.h I also need to use MAX_GROUPS, so do I also define MAX_GROUPS in other.h like this:
other.h
#define MAX_GROUPS 100
struct Other
{
int taco[MAX_GROUPS];
}
The problem is that I'm defining a constant more than one place. I want to keep it all together.
Alternatively, do I reinclude main.h?
other.h
#include "main.h"
struct Other
{
int taco[MAX_GROUPS];
}
The problem here I think its that is creates like a circular dependancy thing. main.h includes other.h which includes main.h which includes other.h which includes etc...
What is the best way to setup the defines and includes for a project so that things sorta cascade down to other included files? Is it common practice to simply do all your defines before your includes?
Minimising circular dependencies is very important in maintaining your project. For an extended discussion, see "Large Scale C++ Software Design" by John Lakos.
To avoid the specific problem you are having, define values in one header file, and include that header file in every file that needs it. To avoid problems with multiple definitions, use include guards:
#ifndef HEADER_THING_H
#define HEADER_THING_H
/* Rest of the header file goes here. */
#endif
That way if it is already included, it is harmless.
Because main.h #includes other.h, it doesn't need to #define MAX_GROUPS again. It'll pick up that definition from the inclusion.
Generally, you should put the defines inside whichever header is relevant -- or where it is primarily used. In this case, you should put MAX_GROUPS inside other.h. By including other.h in main.h, the define will also be picked up (as mentioned by jwismar).
For bigger projects, however, you'd be better off creating a header file containing only your manifest constants (defines) and just include that where needed.
You could also protect your constants against redefinition case by case...
#ifndef MAX_GROUPS
#define MAX_GROUPS 100
#endif
In c lets say we have 2 files
1.h
#include<2.h>
blah blah
and we have
2.h
#include<1.h>
code
How is this resolved??
Typically you protect your include file with an ifndef/define that corresponds to the file name. This doesn't prevent the file from being included again, but it does prevent the contents (inside the ifndef) from being used and triggering the recursive includes again.
#ifndef HEADER_1_h
#define HEADER_1_h
#include "2.h"
/// rest of 1.h
#endif
#ifndef HEADER_2_h
#define HEADER_2_h
#include "1.h"
// rest of 2.h
#endif
Okay, for the sake of completeness I'll begin by quoting tvanfosson's answer:
You should use include guards:
// header1.hpp
#ifndef MYPROJECT_HEADER1_HPP_INCLUDED
#define MYPROJECT_HEADER1_HPP_INCLUDED
/// Put your stuff here
#endif // MYPROJECT_HEADER1_HPP_INCLUDED
However include guards are not meant to solve circular dependencies issues, they are meant to prevent multiple inclusions, which is quite different.
base.h
/ \
header1.h header2.h
\ /
class.cpp
In this case (quite common), you only want base.h to be included once, and that's what include guards give you.
So this will effectively prevents the double inclusion... but you won't be able to compile!!
The problem can be illustrated by trying to reason as the compiler does:
Include "header1.hpp" > this defines the include guard
Include "header2.hpp
Try to include "header1.hpp" but doesn't because the include guard is already defined
Cannot correctly parse "header2.hpp" because the types coming from "header1.hpp" have not been defined yet (since it was skipped)
Back to "header1.hpp", and the types from "header2.hpp" are still missing since they could not be compiled, and thus it fails here too
In the end, you'll left with a big pile of error messages, but at least the compiler does not crash.
The solution is to somehow remove the need for this circular dependency.
Use forward declarations if possible
Split "header1.h" into 2 parts: the part independent from header2 and the other, you should only need to include the former in header2
And THIS will solve the circular dependency (manually) there is no magic going on in the compiler that will do it for you.
Since you posted your question under the c++ tag as well as c, then I am assuming you are using c++. In c++, you can also use the #pragma once compiler directive:
1.h:
#pragma once
#include "2.h"
/// rest of 1.h
2.h:
#pragma once
#include "1.h"
/// rest of 2.h
The result is the same. But there are some notes:
pragma once will usually compile a little faster since it is a higher level mechanism and doesn't happen at preprocessing like include guards
Some compilers have known bugs "dealing" with #pragma once. Though most if not all modern compilers will handle it correctly. For a detailed list see Wikipedia
Edit: I think the directive is also supported in c compilers but have never tried it, and besides, in most c programs I've seen, include guards are the standard (maybe due to compiler limitations handling the pragma once directive?)
Circular inclusions must be eliminated, not "resolved" with include guards (as the accepted answer suggests). Consider this:
1.h:
#ifndef HEADER_1_h
#define HEADER_1_h
#include "2.h"
#define A 1
#define B 2
#endif // HEADER_1_h
2.h:
#ifndef HEADER_2_h
#define HEADER_2_h
#include "1.h"
#if (A == B)
#error Impossible
#endif
#endif // HEADER_2_h
main.c:
#include "1.h"
This will throw the "Impossible" error at compile time, because "2.h" fails to include "1.h" due to include guards, and both A and B become 0. In practice, this leads to hard to track errors which appear and disappear depending on the order in which header files are included.
The right solution here would be to move A and B to "common.h" which then could be included in both "1.h" and "2.h".