The way I usually do it is I make some namespace Platform in Platform.h and every OS call is encapsulated by a static function in this namespace. So the only place in the entire code base that knows what OS is being used is Platform.cpp. Is this a good way of making things easier? For instance when I call Platform::MessageBox(…), what actually happens is:
void Platform::MessageBox(...)
{
#ifdef(_WINDOWS)
....
#elif(_LINUX)
....
#elif(_MAC)
....
#endif
}
1
If you can’t use a platform independent library to take the hard work away from you, then the best option is to keep the complexity of platform independence out of the main application logic by creating a wrapper to encapsulate the platform-dependent code.
When implementing the wrapper, there are two main approaches.
- Use preprocessor macros like you did in the sample code in the question
- Use a separate file for each platform with the code for that platform. Then you use the build system to select the right implementation for the platform you are building for.
I tend to create platform specific libraries so I have common code in one project and by keeping everything in a repository I can go onlinux and pull down common project and compile, pulling in the Linux library and on windows a dll.
This is due to so many libraries being needed for inclusion on each platform, so if I use directx on windows and those libraries and opengl on Linux this pattern helps.