views:

147

answers:

4

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  A: 

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>
Hans Passant
+2  A: 

HINSTANCE and friends are opaque types you know nothing about. This is on purpose, and is a good thing.

HINSTANCE is most likely to be a typedef to PVOID, by the way (source). But theoretically the Win32 API is free to change it in the next version (although the chances of this happening are extremely low), so it isn't a good practice to count on it.

Just include windows.h and be done with it.

Eli Bendersky
+3  A: 

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.

sbi
Yup, Pimpl is how I usually do this.
jalf
Thanks for the suggestion. I never the less have to say that i prefer Alain Rist's solution.
abenthy
+1  A: 

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. cheers, AR

Alain Rist
That's the hack i was searching for, very clever! (`HINSTANCE__` seems to be `struct` here on MSVC2005)
abenthy
It's no hack, Windef.h is written to allow it :-) Declaring a class instead of a struct guarantees a compiler error if Windef.h is included later, which means bad file structure design.
Alain Rist
I see, but if i i use class i get a compiler error if i later include `windows.h` in my implementation file, in which i need `windows.h`. Is it bad file structure to use you're suggested typedef in a header file and include `windows.h` in the corresponding source file?
abenthy
If you need Windows.h in *this* compilation unit, include it at first, as other library headers, before your own.
Alain Rist