I'm writing a portable C++ application. How do I include different headers based on the operating system its running on. Is there a way to do this in C++ or do i have to use the build system?
A header file is a file with extension . h which contains C function declarations and macro definitions to be shared between several source files. There are two types of header files: the files that the programmer writes and the files that comes with your compiler.
There are of 2 types of header file: Pre-existing header files: Files which are already available in C/C++ compiler we just need to import them. User-defined header files: These files are defined by the user and can be imported using “#include”.
A TL;DR definition: A header file must include the header files that directly define each of the types directly used in or that directly declare each of the functions used in the header file in question, but must not include anything else.
In C language, header files contain the set of predefined standard library functions. You request to use a header file in your program by including it with the C preprocessing directive “#include”. All the header file have a '. h' an extension.
I would use the preprocessor directives and a cross-platform build system such as CMake. You could do:
#ifdef LINUX
#include <unistd.h>
#elif defined(WINDOWS)
#include <algorithm.h>
# elif Defined(MAC_OSX)
//... etc.
#else
#error No operating system defined
#endif
Then add the corresponding preprocessor flag to the build, such as: -DLINUX
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With