Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include WinAPI without contaminating the rest of the code?

Tags:

c++

winapi

I'm working on a library in C++ and a part of it is an abstraction layer of several OS functions that i need. I started implementing that with the Windows API but plan to add support for other platforms with #ifdef and such.

What is however starting to become a problem is that including Windows.h propagates to the whole rest of the code where i don't need it and especially, as it is a library, it will also contaminate the code of other people that would use it. I wouldn't really mind if the Windows API used a namespace or some clear way to distinguish its code but instead they #define a lot of pretty common words such as small, near, far (lowercase) and a lot of the function names are also pretty general.

So i would really like if only the platform specific part of my code had access to these and it wouldn't be included anywhere else. I know that the obvious solution would be to only include Windows.h in the CPP files but that isn't always possible because some of the platform specific data types or structures are class member variables such as:

class Window {

public:

    // ...

private:
    HWND handle;

};

So is there a way to accomplish this?

Thanks.

like image 861
Detheroc Avatar asked Oct 27 '25 09:10

Detheroc


1 Answers

Use the pimpl idiom ( http://en.wikipedia.org/wiki/Opaque_pointer ). Limitations of the C++ programming language makes it necessary to use tricks like this in order to get information hiding.

One of the ways of doing that is doing it the same way as you would in C (where you don't have that problem at all, because of the following): Forward-declare a struct in the header file and define its contents in the implementation file.

Most people do that by extracting the entire private part of your example into its own struct, whose contents is only defined in the implementation file, and only put a pointer to it in the header file, as the now only member of the private part of the class.

also, #define WIN32_LEAN_AND_MEAN before the #include in order to strip down what the windows.h gives you.

like image 82
Danny Milosavljevic Avatar answered Oct 28 '25 22:10

Danny Milosavljevic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!