Reputation: 442
There is a header file that I include that only seems to exist on Linux machines, and not on MacOS machines. Although I can use a VM to compile and run the code, it would be nice to be able to do this in MacOS.
To be more specific, I am using #include <endian.h>
, which compiles on Linux, and I would like to use this compatibility header for MacOS, which I would include with #include "endian.h"
. My code compiles and executes as expected with the former include on Linux machines, and with the latter include on MacOS machines.
Is there a way to use platform-specific includes in the header (perhaps using some sort of #if
-based syntax)? Or would this be bad practice?
Upvotes: 0
Views: 332
Reputation:
Is there a way to use platform-specific includes in the header (perhaps using some sort of #if-based syntax)?
yes:
#ifdef __MACH__
... // Mac headers
#elif __unix__
... // these will work for Linux/Unix/BSD even for Mac in most cases
#elif _WIN32
... // windows 32 bit
#elif _WIN64
... // windows 64 bit
#endif
Or would this be bad practice?
I do not think so
The other solution if I remember correctly is installing Command Line Tool
on Mac which will give you all headers for gcc
in Unix
like passion. Here is improvement to my answer, I knew I was forgetting something :( Oh well I only used Mac couple of times for development :S
and here is the reference:
Upvotes: 2
Reputation: 138171
Clang and GCC support the __has_include
preprocessor condition, which you can use instead of testing platform defines:
#if __has_include(<endian.h>)
#include <endian.h>
#else
#include "endian.h"
#endif
One thing to watch for, though, is that as <endian.h>
is not a standard header, it could be possible that it's present on another platform with different definitions that don't really help you.
This is related to this other answer that I wrote a few days ago.
Upvotes: 3