Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i include different headers based on my OS?

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?

like image 957
roshanvid Avatar asked May 24 '11 19:05

roshanvid


People also ask

What are header files in OS?

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.

What are the different header files?

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”.

Can you include header files in header files?

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.

Where is header file?

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.


1 Answers

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.

like image 170
Pete Avatar answered Oct 22 '22 05:10

Pete