I need to maintain a project that supports running on Linux and Windows. Some codes using preprocessor directives like this are fine.
#ifdef _WIN32 // _WIN32 is defined by Windows 32 compilers
#include <windows.h>
#else
#include <unistd.h>
#endif
But some are the actual implementation, which I would like to prevent using preprocessor directives.
void Foo()
{
#ifdef _WIN32 // _WIN32 is defined by Windows 32 compilers
code for windows
#else
code for Linux
#endif
some common code...
#ifdef _WIN32 // _WIN32 is defined by Windows 32 compilers
code for windows again
#else
code for Linux again
#endif
}
So things get convoluted and harder to maintain. Is there any better way?
The traditional way is to “hide” all the code that is specific to any OS in wrapper functions – you can either do that in complete functions that do a higher level functionality – e.g. have a function that returns all directory entries based on a given path as input, or implement the individual base-functions, e.g.
start_read_directory(path),read_dir_entry(),end_read_directory()– that’s just an example functionality, the same principle(s) can be applied on almost any system specific functionality. Wrap it enough, and you wouldn’t be able to tell what you are programming for.In essence, you are doing it wrong if you have a lot of #ifdef in the code itself.