Reincluding header with different #defines - c++

I've been learning more about headers, translation units, and precompiled headers lately. I think I understand them well now. I do have a couple queries though, I'll just ask one here. This is just a theoretical example so it may or may not work in practice, but please try to understand what I'm asking.
Say I have a precompiled header like so:
// stdafx.h
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
and some source file.
// foo.cpp
#include "stdafx.h"
#include <Windows.h>
void bar()
{
// I need to access something in Windows.h that requires
// WIN32_LEAN_AND_MEAN to NOT be defined.
}
It doesn't have to be precompiled headers, but any similar structure in general, though I'm not sure it'd apply otherwise. I can work around this problem with Windows.h easily enough, but I'm sure there are much more difficult situations.
Is it possible in anyway to remove the currently included Windows.h from the precompiled header and reinclude it with adjusted #defines. #undef won't work to my understanding.
The only solution that comes to mind is to create a separate source file and mark it as not using precompiled headers. I'd like to learn of any alternatives.
Also, what would be a more general way to express what I'm asking for the sake of future endeavors and search engine results?

Related

Collect common includes in a single file - good practice?

I am trying to learn how to deal with a lot of includes, and still keep my code tidy.
I am programming a Qt application and I have put files commonly used (and that doesn't change) in a file called "Util.h".
Util.h
#pragma once
#include <Core/IObserver.h>
#include <Core/Math.h>
#include <QAction>
#include <QDockWidget.h>
#include <QFileDialog>
#include <QGraphicsBlurEffect>
#include <QLabel.h>
#include <QMainWindow.h>
#include <QMenu.h>
#include <QMessageBox.h>
#include <QShortcut.h>
#include <QSignalMapper>
#include <QSound>
#include <QString>
#include <QTimer.h>
#include <QTreeView>
#include <QStandardItemModel>
// Path to icons
#define ICON_PATH \
"../../Assets/GUI/Icons/"
This I then include it in almost all of my header files
#include "Util.h"
#include "Manager_Docks.h"
#include "Manager_Tools.h"
#include "Manager_Console.h"
#include "ui_MainWindow.h"
...
Is there a better way of doing it?
Does this slow down compile time much?
I'm also thinking of only including Util.h in every .cpp only, and have a separate Header_Util.h for header files, looking something like this
Header_Util.h
#pragma once
class IObserver;
class QAction;
class QDockWidget;
class QFileDialog;
...
Is this a better solution?
Also, I am aware that there is something called precompiled headers, but have never used myself. Is this perhaps a solution to my problem and something I should look into? I'm on Windows using VS2012 if that makes any difference.
...and to summarize all questions. What would you have done in my place?
TL;DR: Generally, it's best to eliminate unnecessarily visible headers when developing C++ or C.
Is there a better way of doing it?
It's generally a very bad idea when your project is not small. Most sources won't need to see the declaration of most files, and those are high level objects. At least divide it by category.
Does this slow down compile time much?
Generally, yes. Example: Do most of your source files need to know about the UI library? Probably not.
Is this a better solution?
Yes. The forward declarations' cost is very very small.
Also, I am aware that there is something called precompiled headers, but have never used myself. Is this perhaps a solution to my problem and something I should look into?
For some builds, they can save a lot of time. For others, they may only slow things down. If you choose to use them, then measure the build times to confirm which is better for your project and the includes you need.
Typically, you find all your sources don't need to know about something very high level and large (e.g. a GUI library and abstraction layer). Only a portion of the sources generally need to know about those higher level libraries. This is often a good point to break up your codebase into smaller targets/libraries.
...and to summarize all questions. What would you have done in my place?
I wouldn't stuff all those high level libraries/headers in a header for all sources to see. It's painful to undo in large codebases and tends to cost a lot in build times along the way. Headers containing forward declarations are good.
What you're doing is common, although it would be placed within a precompiled header.
A precompiled header (along with a precompiled.cpp) is just a header that will be compile first. The obj file from this compilation can then be directly included into other headers. This prevents all your .cpp files from compiling common header files and cpp files over and over and over again. This speeds up compile times by orders of magnitude.
Setting up a precompiled header is quite simple, and there are quite a few resources online for doing such.

Order of #includes to avoid linking errors

Sometimes in C++ the order of the includes matters. That is the case of openGL using :
1.- Right way:
#include <windows.h> // Header File For Windows
#include <gl\glu.h> // Header File For The GLu32 Library
2.- Wrong way:
#include <gl\glu.h> // Header File For The GLu32 Library
#include <windows.h> // Header File For Windows
Does this happen just for some specific headers or is it kind of a
random problem difficult to prevent a priori?
If that is the case:
How can I know the right order of the includes?
Just some specific headers. Some might call it a design flaw.
You can't. Look at the error messages you get and sort them out carefully. On windows, putting windows.h first is probably a good idea.
The order does not matter for C++ Standard Library includes.
For other libraries it should not usually matter (unless they specifically say so).
For specific platforms, it may matter and it is usually specified clearly when it does.
For ex:
On Windows #include <windows.h> comes before all the other includes.
Also,
#include <stdafx.h>
which is a MSVC++ specific header needs to be included before everything else if you're using precompiled headers.
For windows you need the #include <windows.h> first.
Then in the header files avoid #include - prefer forward declarations instead.
Save less compilation when you just change one header file.
At one time, a fair number of well-known C programmers advised that no header should include any other header -- it should be up to the user to include the correct headers in the correct order to make things work. This worked (and continues to work) pretty well for small projects that don't involve too many headers.
For larger projects, however, keeping track of all the header dependencies can/does become substantially more difficult, to the point that it's nearly unmanageable in many modern code bases. Most modern headers themselves include any other headers upon which they depend.
Unfortunately, that means we frequently end up with a rather confusing mixture of the two. There's not much you can do beyond just dealing with it when it arises, by finding what headers you need to include and in what order.

Multiple inclusion of header files leads to longer compile time?

Does including the same header files multiple times increase the compilation time?
For example, suppose every file in my project uses <iostream> <string> <vector> and <algorithm>. And if I include a lot of files in my source code, then does that increase the compile time?
I always thought that the guard headers served important purpose of avoiding double definitions but as a by product also eliminates double code.
Actually, someone I know proposed some ideas to remove such multiple inclusions. However, I consider them to be completely against the good design practices in c++. But was still wondering what might be the reasons of him to suggest the changes?
Most of these answers are wrong... For modern compilers, there is zero overhead for including the same file multiple times, assuming the header uses the usual "include guard" idiom.
The GCC preprocessor, for example, has special code to recognize the include guard idiom. It will not even open the header file (never mind reading it) for the second and subsequent #include directives.
I am not sure about other compilers, but I would be very surprised if most of them did not implement the same optimization.
Another technique besides precompiled headers is the compiler firewall idiom, explained here:
http://www.gotw.ca/publications/mill04.htm
http://www.gotw.ca/publications/mill05.htm
Every time #include <something.h> occurs in your source file, 'something.h' have to be found along the include path and read. But there is #ifndef _SOMETHING_H_ check, so the content of such something.h would not be compiled.
Thus there is some overhead, but it is really small.
If compile times were an issue, people used to use the optimisation recommended by Praetorian, originally recommened in Large Scale Software Design. However, most modern compilers automatically optimise for this case. For example, see the help from gcc
The best is to use precompiled headers. I do not know which compiler you are using, but most of them have this feature. I suggest you to refer to your compiler-manual on how to achieve this.
It basically collects all headerfiles and compiles it into a object file which then can be used by the linker. That speeds up compiling very much.
Minor Drawback:
You need to have 1 "uberheader" which is included in every compilation-unit (.cpp).
In that uberheader, only include static headers from libraries, not your own. Then the compiler does not need to recompile it very often.
It helps esp. when using header-only libraries such as boost or glm, eigen etc.
HTH
Yes, including the same header multiple times means that the file needs to be opened before the preprocessor guards kick in and prevent multiple definitions. The Mozilla source code uses the following trick to prevent this:
Foo.h
#ifndef FOO_H
#define FOO_H
// whatever
#endif /* FOO_H */
In all files that need to include foo.h
#ifndef FOO_H
#include "foo.h"
#endif
This prevents foo.h from having to be opened multiple times. Of course, this depends on everyone following a particular naming convention for their preprocessor guards.
You can't do this with standard headers, since there is no common naming convention for their preprocessor guards.
EDIT:
After reading your question again, I think you're asking about the same header being included in different source files. What I talked about above does not help with that. Each header file will still have to be opened and included at least once in every translation unit. The only way I know of to prevent this is to use precompiled headers, as #scorcher24 mentioned in his answer. But I'd stay away from this solution, because there is no standard way of generating precompiled headers across compilers, unless the compile times are absolutely prohibitive.
Some compilers, most notably Microsoft's, have a #pragma once directive that you can use to automatically skip an include file once it's already been included. This removes any performance penalty.
http://en.wikipedia.org/wiki/Pragma_once
It can be an issue. As others have said, most modern compilers
handle the case intelligently, and will only re-open the file in
degenerate cases. Most is not all, however, and one of the major
exceptions is Microsoft, which a lot of people do have to support. The
surest solution (if this is really a problem in your environment) is to
use the Lakos convention, putting the include guards around the
#include as well as in the header. This means, of course, a standard
convention for generating the guard names. (For external includes, wrap
them in your own header, which respects your local convention.)
Alternatively, you can use both the guards and #pragma once. The
guards will always work, and most compilers will avoid the extra opens,
and #pragma once will usually avoid the extra opens with Microsoft.
(#pragma once cannot be implemented reliably in complex networked
situation, but as long as all of your files are on your local drive,
it's quite reliable.)

Wrapping #includes in #ifndef's - adds any value?

I have inherited C/C++ code base, and in a number of .cpp files the #include directives are wrapped in #ifndef's with the headers internal single include #define.
for example
#ifndef _INC_WINDOWS
#include <windows.h>
#endif
and windows.h looks like
#ifndef _INC_WINDOWS
#define _INC_WINDOWS
...header file stuff....
#endif // _INC_WINDOWS
I assume this was done to speed up the compile/preprocess of the code.
I think it's ugly and a premature optimisation, but as the project has a 5 minute build time from clean, I don't want to makes things worse.
So does the practice add any value or speed things up lots? Is it OK to clean them up?
Update: compiler is MSVC (VS2005) and platform is Win32/WinCE
It's worth knowing that some implementations have #pragma once and/or a header-include-guard detection optimisation, and that in both cases the preprocessor will automatically skip opening, reading, or processing a header file which it has included before.
So on those compilers, including MSVC and GCC, this "optimisation" is pointless, and it should be the header files responsibility to handle multiple inclusion. However, it's possible that this is an optimisation for compilers where #include is very inefficient. Is the code pathologically portable, and <windows.h> refers not to the well-known Win32 header file, but to some user-defined header file of the same name?
It's also possible that the header files don't have multiple-include guards, and that this check is actually essential. In which case I'd suggest changing the headers. The whole point of headers is as a substitute for copy-and-pasting code about the place: it shouldn't take three lines to include a header.
Edit:
Since you say you only care about MSVC, I would either:
do a mass edit, time the build just to make sure the previous programmer doesn't know something I don't. Maybe add #pragma once if it helps. Use precompiled headers if all this really is slowing things down.
Ignore it, but don't use the guards for new files or for new #includes added to old files.
Depending on whether I had more important things to worry about. This is a classic Friday-afternoon job, I wouldn't spend potentially-productive time on it ;-)
If a file is included, then that whole file has to be read, and even the overhead of opening/closing the file might be significant. By putting the guarding directives around the include statement, it never has to be opened. As always with these questions, the correct answer is: try taking out the ifndef/endif guards around the include directives and get your stopwatch...

Other's library #define naming conflict

Hard to come up with a proper title for this problem. Anyway...
I'm currently working on a GUI for my games in SDL. I've finished the software drawing and was on my way to start on the OpenGL part of it when a weird error came up. I included the "SDL/SDL_opengl.h" header and compile. It throws "error C2039: 'DrawTextW' : is not a member of 'GameLib::FontHandler'", which is a simple enough error, but I don't have anything called DrawTextW, only FontHandler::DrawText. I search for DrawTextW and find it in a #define call in the header "WinUser.h"!
//WinUser.h
#define DrawText DrawTextW
Apparently it replaces my DrawText with DrawTextW! How can I stop it from spilling over into my code like that?
It's a minor thing changing my own function's name, but naming conflicts like this seem pretty dangerous and I would really like to know how to avoid them all together.
Cheers!
You have a couple of options, all of which suck.
Add #undef DrawText in your own code
Don't include windows.h. If another library includes it for you, don't include that directly. Instead, include it in a separate .cpp file, which can then expose your own wrapper functions in its header.
Rename your own DrawText.
When possible, I usually go for the middle option. windows.h behaves badly in countless other ways (for example, it doesn't actually compile unless you enable Microsoft's proprietary C++ extensions), so I simply avoid it like the plague. It doesn't get included in my files if I can help it. Instead, I write a separate .cpp file to contain it and expose the functionality I need.
Also, feel free to submit it as a bug and/or feedback on connect.microsoft.com. Windows.h is a criminally badly designed header, and if people draw Microsoft's attention to it, there's a (slim) chance that they might one day fix it.
The good news is that windows.h is the only header that behaves this badly. Other headers generally try to prefix their macros with some library-specific name to avoid name collisions, they try to avoid creating macros for common names, and they try avoid using more macros than necessary.
It's an unfortunate side effect of #includeing <windows.h>. Assuming you're not actually using Windows' DrawText() anywhere in your program, it's perfectly safe to #undef it immediately after:
// wherever you #include <windows.h>, or any other windows header
#include <windows.h>
#undef DrawText
There is no general way of avoiding this problem - once you #include a header file using the preprocessor it can redefine any name it likes, and there is nothing you can do about it. You can #undef the name, but that assumes you know the name was #defined in the first place.
Just #undef the symbols you don't want. But Make sure that you include windows.h and do this before you include SDL:
#include <windows.h>
#undef DrawText
#include <SDL/SDL_opengl.h>