Ok, I have this scenario.
A class called a which includes windows.h.
#ifndef a.h
#define a.h
#include <windows.h>
class a
{
};
#endif
A class called b which includes windows.h.
#ifndef b.h
#define b.h
#include <windows.h>
class b
{
};
#endif
A main class as such.
#include "a.h"
#include "b.h"
MAIN STUFF
The point I'd like to clarify is the following.开发者_运维技巧
Because I am importing both a and b into main, I am concerned that windows.h is being included twice. Is this so? If so, how to fix?
#windows.h
should be (read: is) clever enough that this is not a problem.
They use "header guards" to guarantee safety of multiple inclusion within a TU, the same way you did in your files
a.h
andb.h
(though you should really pick better names for those guards... oh how easily they can conflict at present!).To guarantee safety of multiple inclusion across TUs (not your scenario at the moment), they restrict themselves to only allowing declarations, not definitions, in header files. The rest will go in the library binaries that are part of your operating system. (And, in fact, aside from template/inline function definitions, you should always stray from defining things in headers).
Take a look at the first two lines in your own header files. Together, those lines make sure that the C preprocessor only includes each header file once. This is the standard way headers should be written for C/C++ software. Main system headers, like windows.h, do the same (or something similar) to make sure that the preprocessor only sees a file once.
There should be no worries as the windows.h
include file has guards in it. If you do get errors, switch compiler versions or compilers in general.
windows.h is not getting included more than once.
indeed, c/c++ header files adopt the convention of protecting inclusion by means of an #ifdef guard block, like this:
#ifndef __WINDOWS_H__
#define __WINDOWS_H__
...
... <windows.h content>
...
#endif
so that the is actually included just once
Yes, but no worries as the start of windows.h is:
#ifndef _WINDOWS_
#define _WINDOWS_
As an aside, you might want to also
#define WIN32_LEAN_AND_MEAN
before the windows include, to keep out some of the more esoteric features.
I'm 99% sure, that windows.h
has include guards, so it should be totally safe to include a.h
and b.h
into one file - the things in windows.h
will not be duplicated
This shouldn't be a problem because an important header file like Windows.h
will also include a guard at the beginning like
#ifndef _WINDOWS_H
#define _WINDOWS_H
//...code
#endif // _WINDOWS_H
So the information in the Windows.h
header file will only be included once for each compiled code module, even if the header is repeated multiple times, since after the first time it's included, _WINDOWS_H
is defined, therefore the guards cause the preprocessor to skip the content of the remaining Windows.h
files.
精彩评论