I’m looking for a pattern to organize header files for multiple platforms in C++.
I have a wrapper .h file that should compile under both Linux and Win32.
Is this the best I can do?
// defs.h
#if defined(WIN32)
#include <win32/defs.h>
#elif defined(LINUX)
#include <linux/defs.h>
#else
#error "Unable to determine OS or current OS is not supported!"
#endif
// Common stuff below here...
I really don’t like preprocessor stuff in C++. Is there a clean (and sane) way to do this better?
You should use a configuration script able to perform platform checks and generate the appropriate compiler flags and/or configuration header files.
There are several tools able to perform this task, like autotools, Scons, or Cmake.
In your case, I would recommend using CMake, as it nicely integrates with Windows, being able to generate Visual Studio project files, as well as Mingw makefiles.
The main philosophy behind these tools is that you do not test again the OS itself, but against features that might or might not be present, or for which values can vary, reducing the risk that your code fails to compile with a “platform non supported” error.
Here is a commented CMake sample (CMakeFiles.txt):
With that, you have to provide a config-cmake.h.in template that will be processed by cmake to generate a config.h file containing the definitions you need:
I invite you to go to the cmake website to learn more about this tool.
I’m personally a fan of cmake, which I’m using for my personal projects.