So I know how to place an include guard in my own header files with the standard
#ifndef ...
#define ...
Now, My question is about including libraries that are not my own. would be a good example. I have a header file which requires the use of string, so I do the following
foo.h
#ifndef FOO_H
#define FOO_H
#include <string>
... code etc ...
#endif
Now, if I have another header file called.. lets say, bar.h, which ALSO requires the use of <string>, how can i prevent multiple inclusions? Does the STL already have include guards in place?
The STL library also has include guards and any good library should do the same.
#ifndef _GLIBCXX_STRING
#define _GLIBCXX_STRING 1
This is from gcc's
Assuming that by "STL" you mean the C++ standard library, then you can refer to the C++ standard. ยง17.6.2.2/2 states:
A translation unit may include library headers in any order. Each may be included more than once, with no effect different from being included exactly once, except that the effect of including either <cassert> or <assert.h> depends each time on the lexically current definition of NDEBUG.
This means that it is not necessary to guard against multiple inclusions of the same header.
Include guard use to guard the content inside the guard pair. You can check the system head file string, it also has the include guard. So, don't worry about multiple inclusions.
Related
Lets say I am using header guards,
#ifndef MAIN_H
#define MAIN_H
#include "foo.h"
#include "some_header_file.h"
... // Some Code
#endif
Inside foo.h file also with Header guards.
#ifndef FOO_H
#define FOO_H
#include "some_header_file.h"
... // Some Code
#endif
As you can see main file have 2 headers one of them is dublicate. I have three questions:
Does Header guards prevent duplicate header files?
Does the compiler optimize it and removes it?
Is this a bad practice and the extra header file should be deleted from main file?
Does Header guards prevent duplicate header files?
Yes. The first encountered inclusion will bring the content of the header to the translation unit, and the header guard causes successive inclusions to be empty which prevents the content of the header from being duplicated. This is exactly the reason why header guards are used.
or is this a bad practice and the extra header file should be deleted from main file?
No, the duplicate inclusion is not a bad practice. If the "main" header depends on any declaration from "some_header_file.h", then "main" absolutely should include "some_header_file.h" directly, whether another header - even one included by "main" - also includes it or not.
Relying on a transitive inclusion would generally be a bad practice - i.e. in this case it may be bad to rely on the detail that "foo.h" includes "some_header_file.h" when including "foo.h" into "main". Such assumptions often can cause programs to break unexpectedly when they are modified. In this case, if "foo.h" was modified to no longer depend on "some_header_file.h", and that inclusion was removed, then that change would suddenly cause the assumption to fail, and "some_header_file.h" would no longer be included into "main" as a result of change that didn't involve "main" at all. That would be bad.
The main problem with repited includes is when two different files include each other. For example, if a.h include b.h, and b.h includes a.h, if you don't add header guards, preprocessor ends up in a cycle, because every time it reads a.h includes b.h, and b.h includes a.h, and this never ends.
In your case you could have some problem if you define a variable in your some_header_file.h", because it would be read twice and the variables would be declared twice also, which would result in a compiler error.
You need to add them in "some_header_file.h", that way next time preprocessor reads this file it would ignore it by the ifndef clause. And notice the importance for cyclic include dependencies.
In "some_header_file.h" add:
#ifndef SOME_HEADER_FILE_H
#define SOME_HEADER_FILE_H
...code
#endif /* SOME_HEADER_FILE_H */
Last comment isn't necessary, but it helps case you need to debug/review preprocessors output.
Let's say we have two class, Foo and Bar.
in Foo.h
#ifndef MYPROJ_FOO
#define MYPROJ_FOO
....
# endif
in Bar.cpp, do we still need to guard the include such as
#ifndef MYPROJ_FOO
#include <Foo.h>
#endif
or simple #include is sufficient? It seems redundant to me to have include guard if we already have header guard, but I see such practice quite often, hence wondering if I'm missing something. Thanks!
Functionally, it does not make any difference.
A reason why old code may be using this is as an optimisation. It means the preprocessor can avoid reading Foo.h a second time, so it can generate the result a little bit faster.
Nowadays, even if the preprocessor does read the file a second time, the performance impact of that should be small enough not to bother with it. Some preprocessors may even detect header guards automatically, remember which header guard is associated with which macro, and avoid re-reading the header file all by themselves.
No, you should not. Include guards are for headers, which are included by other files. Source files, on the other hand, should never be included by other files.
Alternatively you may consider using the (non standard, but generally accepted) extension in your header files
#pragma once
in Bar.cpp, do we still need to guard the include such as
#ifndef MYPROJ_FOO
#include <Foo.h>
#endif
or simple #include is sufficient?
Simple #include is sufficient from a correctness point of view.
It seems redundant to me to have include guard if we already have header guard, but I see such practice quite often, hence wondering if I'm missing something.
The practice was recommended by John Lakos in his book Large Scale C++ Software Design.
However, a better alternative is to use the #pragma once directive, which is supported by most modern C++ compilers.
Foo.h:
#pragma once
....
Then, you can just use
#include "Foo.h"
in any .cpp file.
or simple #include is sufficient?
Yes, it is.
It seems redundant to me to have include guard if we already have header guard,
Yes it is totally redundant.
but I see such practice quite often
I don't see such practiced, unless the codes authors have no clue what they're doing.
What happens if I include iostream or any other header file twice in my file?
I know the compiler does not throw error.
Will the code gets added twice or what happens internally?
What actually happens when we include a header file ?
Include guard prevents the content of the file from being actually seen twice by the compiler.
Include guard is basically a set of preprocessor's conditional directives at the beginning and end of a header file:
#ifndef SOME_STRING_H
#define SOME_STRING_H
//...
#endif
Now if you include the file twice then first time round macro SOME_STRING_H is not defined and hence the contents of the file is processed and seen by the compiler. However, since the first thing after #ifdef is #define, SOME_STRING_H is defined and the next time round the header file's content is not seen by the compiler.
To avoid collisions the name of the macro used in the include guard is made dependent on the name of the header file.
Header files are simple beasts. When you #include <header> all that happens is that the contents of header basically get copy-pasted into the file. To stop headers from being included multiple times, include guards are used, which is why in most header files you'll see something akin to
#ifndef SOME_HEADER_FILE_GUARD
#define SOME_HEADER_FILE_GUARD
//Contents of Header
#endif
It simply gets skipped over, due to preprocessor code along the following lines:
#ifndef MY_HEADER_H
#define MY_HEADER_H
<actual header code here>
#endif
So if you include twice, then MY_HEADER_H is already defined and everything between the #ifndef and #endif is skipped by the preprocessor.
It depends. With the exception of <assert>, the standard requires the
second (and later) includes of a standard header to be a no-op. This is
a characteristic of the header, however; the compiler will (at least
conceptually) read and include all of the header text each time it
encounters the include.
The standard practice for avoiding multiple definitions in such cases is
to use include guards: all of the C++ code in the header will be
enclosed in something like:
#ifndef SPECIAL_NAME
#define SPECIAL_NAME
// All of the C++ code here
#endif SPECIAL_NAME
Obviously, each header needs a different name. Within an application,
you can generally establish conventions based on the filename and
location; something like subsystem_filename, with
characters not legal in a C++ symbol (if you're using them in your
filenames) mapped (and very often everything upper cased). For
libraries, the best practice would be to generate a reasonably long
random sequence of characters; far more frequent (although certainly
inferior from a quality of implementation standpoint) is to ensure that
every such symbol begin with a documented prefix.
A system library can, of course, use reserved symbols (e.g. a symbol
starting with an underscore followed by a capital letter) here, to
guarantee that there is no conflict. Or it can use some entirely
different, implementation dependent technique. Microsoft, for example,
uses a compiler extension #pragma once; g++ uses include guards which
always start with _GLIBCXX (which isn't a legal symbol in user code).
These options aren't necessarily available to you.
When you include a header file, all its contents get copied to the line where the "#include" directive was placed. This is done by the preprocessor and is a step in the compilation process.
This process is the same for standard files like iostream or user-made ".h" files stored in local directory. However, the syntax slightly differs.
We use #include <filename> for files like 'iostream' which are stored in the library. Whereas, for header files in the local directory, we use #include "filename.h".
Now, what if we include header files twice:
Ideally speaking the content should be copied twice. But...
Many header files use the modern practice of mentioning #pragma once which instructs the pre-processor to copy contents only once, no matter how many times the header file is included.
Some very old codes use a concept called 'include gaurds'. I won't explain it as the other answers do so very well.
Using pragma once is the easy and the modern approach, however, include guards were used a lot previously and is a relatively complicated fix to this issue.
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".
In eclipse, whenever I create a new C++ class, or C header file, I get the following type of structure. Say I create header file example.h, I get this:
/*Comments*/
#ifndef EXAMPLE_H_
#define EXAMPLE_H_
/* Place to put all of my definitions etc. */
#endif
I think ifndef is saying that if EXAMPLE_H_ isn't defined, define it, which may be useful depending on what tool you are using to compile and link your project. However, I have two questions:
Is this fairly common? I don't see it too often. And is it a good idea to use that rubric, or should you just jump right into defining your code.
What is EXAMPLE_H_ exactly? Why not example.h, or just example? Is there anything special about that, or could is just be an artifact of how eclipse prefers to auto-build projects?
This is a common construct. The intent is to include the contents of the header file in the translation unit only once, even if the physical header file is included more than once. This can happen, for example, if you include the header directly in your source file, and it's also indirectly included via another header.
Putting the #ifndef wrapper around the contents means the compiler only parses the header's contents once, and avoids redefinition errors.
Some compilers allow "#pragma once" to do the same thing, but the #ifndef construct works everywhere.
This is just a common way to protect your includes - in this way it prevents the code from being included twice. And the identifier used could be anything, it's just convention to do it the way described.
Is it common? Yes - all C and C++ header files should be structured like this. EXAMPLE_H is a header guard, it prevents the code in the header being included more than once in the same translation unit, which would result in multiple definition errors. The name EXAPMLE_H is chosen to match the name of the header file it is guarding - it needs to be unique in your project and maybe globally as well. To try to ensure this, it's normal to prefix or suffix it with your project name:
#define MYPROJ_EXAMPLE_H
for example, if your project is called "myproj". Don't be tempted into thinking that prefixing with underscores will magically make it unique, by the way - names like _EXAMPLE_H_ and __EXAMPLE_H__ are illegal as they are reserved for the language implementation.
Always do this at the top of a header file. It's typically called a header guard or an include guard.
What it does is make it so that if a header file would be included multiple times, it will only be included once. If you don't do it, then you'll end up with errors about things being defined multiple times and things like that.
The exact define doesn't matter that much, though typically it's some variation on the file name. Basically, you're checking whether the given macro has been defined. If it hasn't, then define it, and continue with including the file. If it has, then you must have included the file previously, and the rest of the file is ignored.
This is an include guard. It guarantees that a header is included no more than once.
For example, if you were to:
#include "example.h"
#include "example.h"
The first time the header is included, EXAMPLE_H_ would not be defined and the if-block would be entered. EXAMPLE_H_ is then defined by the #define directive, and the contents of the header are evaluated.
The second time the header is included, EXAMPLE_H_ is already defined, so the if-block is not re-entered.
This is essential to help ensure that you do not violate the one definition rule. If you define a class in a header that didn't have include guards and included that header twice, you would get compilation errors due to violating the one definition rule (the class would be defined twice).
While the example above is trivial and you can easily see that you include example.h twice, frequently headers include other headers and it's not so obvious.
Consider this
File foo.c:
#include foo.h
#include bar.h
File bar.h
#include <iostream>
#include foo.h
Now, when we compile foo.c, we have foo.h in there twice! We definitely don't want this, because all the functions will throw compile errors the second time around.
To prevent this, we put the INCLUDE GUARD at the top. That way, if it's already been included, we define a preprocessor variable to tell us not to include it again.
It's very common (often mandated), and very frustrating if someone doesn't put one in there. You should be able to simply expect that each .h file has a header guard when you included. Of course, you know what they say when you assume things ("makes an ass of u and me") but that should be something you're expecting to see.
This is called an include guard and is indeed a common idiom for C/C++ header files. This allows the header file to be included multiple times without multiply including its contents.
The name EXAMPLE_H_ is an arbitrary convention but has to obey naming rules for C preprocessor macros, which excludes names like example.h. Since C macros are all defined in a single global namespace, it is important that you do not have different header files that use the same name for their include guard. Therefore, it is usually a good idea to include the name of your project or library in the include guard name:
#ifndef __MYPROJECT_EXAMPLE_H__
...