Intrusive defines in windows headers - c++

What is the best way to deal with intrusive #defines in windows headers? They tend to emit errors when I really need to define a symbol with the same name, no matter if it is in a namespace or not. I know some defines can be avoided with WIN32_LEAN_AND_MEAN, but not all. In this particular case, I'm hitting a "DELETE" define in WinNT.h#6478 - and there are tons of pretty generic keywords like this.
My immediate thought is to do an #undef before declaring my constant, but that is a very unelegant solution. I can't easily rename my constants because they are directly translated to text strings and I need those to be exactly what they are now.
Other defines that come to mind are GetFirstChild/GetNextSibling in windowsx.h ... really?

Realistically, I think the cleanest solution would be to provide a wrapper header that would #include <windows.h> and #undef all the macros that are getting in your way. You would then include this wrapper header instead of windows.h.

The obvious solution is not to include <windows.h>. There
should be very, very few modules which need it, and in those,
you just have to avoid the symbols which <windows.h> defines.
Which shouldn't be too difficult, because those will be low
level wrappers which don't need to include anything of your
application.

My solution would be "don't include <windows.h> unless it's absolutely necessary". In general, you want to isolate the system dependencies to a small set of code anyway, so including <windows.h> in files willy-nilly is a bad idea.

Related

Reincluding header with different #defines

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?

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.

Include everything, Separate with "using"

I'm developing a C++ library. It got me thinking of the ways Java and C# handle including different components of the libraries. For example, Java uses "import" to allow use of classes from other packages, while C# simply uses "using" to import entire modules.
My questions is, would it be a good idea to #include everything in the library in one massive include and then just use the using directive to import specific classes and modules? Or would this just be down right crazy?
EDIT:
Good responses so far, here are a few mitigating factors which I feel add to this idea:
1) Internal #includes are kept as normal (short and to the point)
2) The file which includes everything is optionally supplied with the library to those who wish to use it3) You could optionally make the big include file part of the pre-compiled header
You're confusing the purpose of #include statements in C++. They do not behave like import statements in Java or using statements in C#. #include does what it says; namely, loads and parses the entire indicated file as part of the current translation unit. The reason for the separate includes is to not have to spend compilation time parsing the entire standard library in every file. In contrast, the statements you're trying to make #include behave like are merely for programmer organization purposes.
#include is for management of the compilation process; not for separating uses. (In fact, you cannot use seperate headers to enforce seperate uses because to do so would violate the one definition rule)
tl;dr -> No, you shouldn't do that. #include as little as possible. When your project becomes large, you'll thank yourself when you're not waiting many hours to compile your project.
I would personally recommend only including the headers when you need them to explicitly show which functionalities your file requires. At the same time, doing so will prevent you from gaining access to functionalities you might no necessarily want, e.g functions unrelated to the goal of the file. Sure, this is no big deal, but I think that it's easier to maintain and change code when you don't have access to unnecessary functions/classes; it just makes it more straightforward.
I might be downvoted for this, but I think you bring up an interesting idea. It would probably slow down compilation a bit, but I think the concept is neat.
As long as you used using sparingly — only for the namespaces you need — other developers would be able to get an idea of what classes were used in a file by glancing at the top. It wouldn't be as granular as seeing a list of #included files, but is seeing a list of included header files really very useful? I don't think so.
Just make sure that all of the header files all use inclusion guards, of course. :)
As said by #Billy ONeal, the main thing is that #include is a preprocessor directive that causes a "^C, ^V" (copy-paste) of code that leads to a compile time increase.
The best considered policy in C++ is to forward declare all possible classes in ".h" files and just include them in the ".cpp" file. It isolates dependencies, as a C/C++ project will be cascadingly rebuilt if a dependent include file is changed.
Of course M$ compilers and its precompiled headers tend to do the opposite, enclosing to what you suggest. But anyone that tried to port code across those compilers is well aware of how smelly it can go.
Some libraries like Qt make extensive use of forward declarations. Take a look on it to see if you like its taste.
I think it will be confusing. When you write C++ you should avoid making it look like Java or C# (or C :-). I for one would really wonder why you did that.
Supplying an include-all file isn't really that helpful either, as a user could easily create one herself, with the parts of the library actually used. Could then be added to a precompiled header, if one is used.

C++: Is windows.h generally an efficient code library?

I heard some people complaining about including the windows header file in a C++ application and using it. They mentioned that it is inefficient. Is this just some urban legend or are there really some real hard facts behind it? In other words, if you believe it is efficient or inefficient please explain how this can be with facts.
I am no C++ Windows programmer guru. It would really be appreciated to have detailed explanations.
*Edit: I want to know at compile time and execution. Sorry for not mentioning it.
windows.h is not a "code library". It's a header file, and doesn't contain any executable code as such (save for macro definitions, but those still aren't compiled - their expansions are, if and when you use them).
As such, looking at it strictly from performance perspective, merely including it has any effect solely on compilation time. That one is rather significant, though - for example, if using Platform SDK headers that come with VS2010, #include <windows.h> expands to ~2.4Mb of code - and all that code has to be parsed and processed by the compiler.
Then again, if you use precompiled headers (and you probably should in this scenario), it wouldn't affect you.
If you precompile it, then the compilation speed difference is barely noticeable. The downside to precompiling, is that you can only have one pre-compiled header per project, so people tend to make a single "precompiled.h" (or "stdafx.h") and include windows.h, boost, stl and everything else they need in there. Of course, that means you end up including windows.h stuff in every .cpp file, not just the ones that need it. That can be a problem in cross-platform applications, but you can get around that by doing all your win32-specific stuff in a static library (that has windows.h pre-compiled) and linking to that in your main executable.
At runtime, the stuff in windows.h is about as bare-metal as you can get in Windows. So there's really no "inefficiencies" in that respect.
I would say that most people doing serious Windows GUI stuff would be using a 3rd-party library (Qt, wxWidgets, MFC, etc) which is typically layered on top of the Win32 stuff defined in windows.h (for the most part), so as I said, on Windows, the stuff in windows.h is basically the bare metal.
There are multiple places where efficiency comes in to play.
Including <windows.h> will substantially increase compile times and bring in many symbols and macros. Some of these symbols or macros may conflict with your code. So from this perspective, if you don't need <windows.h> it would be inefficient at compile time to bring it in.
The increased compile time can be mitigated somewhat by using precompiled headers, but this also brings with it a little more codebase complexity (you need at least 2 more files for the PCH), and some headaches unique to PCHs. Nonetheless, for large Windows project, I usually use a PCH. For toy or utility projects, I typically don't because it's more trouble than it's worth.
Efficiency also comes in to play at runtime. As far as I know, if you #include <windows.h> but don't use any of those facilities, it will have no effect on the runtime behavior of your program at least as far as calling extra code and that kind of thing. There may be other runtime effects however that I'm not aware of.
As far as the big White Elephant question, "Is Windows Efficient?" I'll not go in to that here other than to say this: Using Windows is much like anything else in that how efficient or inefficient it is depends mostly on you and how well you know how to use it. You'll get as many different opinions on this as people you ask however, ranging from "Winblowz sucks" to "I love Windows, it's awesome." Ignore them all. Learn to code in Windows if you need & want to and then make up your own mind.
As has been noted, #including windows.h slows down compile time. You can use precompiled headers or do a good job of isolating the windows calls only to modules that need them to help with that.
Also, you can add these preproc definitions before the windows.h include like so:
#define WIN32_LEAN_AND_MEAN
#define VC_EXTRALEAN
#include <windows.h>
It will reduce the number of definitions from windows.h and sub-included header files. You may find later on that you need to remove the lean-and-mean, but try it first and wait until the compiler complains about a missing def.
The namespace conflicts are a legitimate gripe, but technically have nothing to do with efficiency, unless you count efficiency of your personal use of time. Considering how many thousands of definitions will be thrown into your namespace, conflicts are bound to occur at some point, and that can be severely irritating. Just use the practice of isolating your Windows calls into modules, and you will be fine. For this, put #include windows.h in the .cpp file, and not the .h file.
I see no basis for thinking that the runtime performance of the executable will be impacted by including windows.h. You are only adding a large number of definitions to the context used by the compiler. You aren't even putting all the definitions into your compiled code--just allocations, function calls, and referencing based on any definitions used in your source code (.cpp).
Another argument could be made that the Windows API types and functions are inherently wasteful of resources or perform inefficiently. I.e. if you want to create a file, there is some monstrous structure to pass to the Windows API. Still, I think most of this is penny-wise/pound-foolish thinking. Evaluate Windows API performance problems case-by-case and make replacements for inefficient code where possible and valuable.
In general, including windows.h is a necessity: if you need windows functions, you have to include it. I think what you're refering to is (among other things) nested inclusion of windows.h. That is, you include a .h that includes itself windows.h, and you also include windows.h in your .cpp file. This leads to inefficiencies, of course, so you have to study very well in your code what .h files are included in each .h file, and avoid including, say, windows.h n times indirectly.
Just including the header without using it will not have any effects in runtime efficiency
It would affect compilation time ..

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>