Forward declare HINSTANCE and friends

2020-07-07 08:38发布

问题:

Is there a way to forward-declare the HINSTANCE type from the WinAPI without including the full (and big) windows.h header?

For example, if I have a class RenderWindow which owns an HINSTANCE mInstance, i will have to include windows.h in RenderWindow.h. So everything that needs RenderWindow also has to include windows.h.

I tried including windef.h but this seems to need some things from windows.h. :-( If I can't forward declare it, is there at least a portable way to use something like long mInstance in RenderWindow instead of HINSTANCE?

回答1:

HINSTANCE is declared in WinDef.h as typedef HINSTANCE__* HINSTANCE;

You may write in your headers:

#ifndef _WINDEF_
class HINSTANCE__; // Forward or never
typedef HINSTANCE__* HINSTANCE;
#endif

You will get compilation errors referencing a HINSTANCE when WinDef.h is not included.



回答2:

You could declare it void* and cast the errors away. This is close to a never-ending battle though, sooner or later you'll get tripped up. Use pre-compiled headers so you don't care about the size of windows.h

stdafx.h:

#define WIN32_LEAN_AND_MEAN
#include <windows.h>


回答3:

For example, if I have a class RenderWindow which owns an HINSTANCE mInstance, i will have to include windows.h in RenderWindow.h. So everything that needs RenderWindow also has to include windows.h.

Have you looked at the Pimpl idiom? This allows you to hide private members. A side-effect is that you don't have to include their headers in your class' header.