Undefine already included header - c++

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.

Related

Is using headers multiple times bad?

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.

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).

Header should be included once

In header files I've seen two main ways for defining macro to avoid including the file more than once.
1.
#ifndef SOME_CLASS
#define SOME_CLASS
//code ...
#endif
2.
#ifndef SOME_CLASS
//code...
#define SOME_CLASS
#endif
Which is more preferable and why?
I prefer the first method, because it doesn't matter what happens after the ifndef because it will be defined straight after.
The first option is commonly optimized by compilers to behave like the non-standard #pragma once.
It is also safer in case of recursive includes. If, in the //code... part, you include another header which includes .... which includes the header you're currently editing, then the second version won't work.
I'd go for the first one.
Reason: If you ever want to change the guard name (say, SOME_CLASS to SOMECLASS), you don't have to scroll all the way down to the end of file to change it too.
The best option is to use #pragma once. With #define you must be very careful when using multiple libraries as the guard name may not be unique.
I prefer the first option. Suppose you include more files, and these files in turn include the file containing #ifndef SOME_CLASS.
I think it's fairly easy to spot include errors, if the #define SOME_CLASS isn't adjacent to #ifndef SOME_CLASS.
// SomeClass.h
#ifndef SOME_CLASS
#include "OtherFile.h" // will eventually lead to #include "SomeClass.h"
#define SOME_CLASS
... boat load of code here...
#endif // SOME_CLASS

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

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.

How are circular #includes resolved?

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".