Conditional compilation in C ++ based on the operating system

I would like to write a cross-platform function in C ++ that contains system calls. What conditional compilation flags can be checked to determine which operating system compiles the code? I'm mainly interested in Windows and Linux using Visual Studio and GCC.

I think it should look something like this:

void SomeClass::SomeFunction() { // Other code #ifdef LINUX LinuxSystemCall(); #endif #ifdef WINDOWS WindowsSystemCall(); #endif // Other code } 
+6
linux windows cross-platform visual-studio conditional-compilation
source share
4 answers

My gcc (4.3.3) defines the following predefined macros related to Linux:

 $ gcc -dM -E - < /dev/null | grep -i linux #define __linux 1 #define __linux__ 1 #define __gnu_linux__ 1 #define linux 1 

VC ++ (and many other Win32 compilers) also have a couple of predefined macros that identify the platform, primarily _WIN32. Additional information: http://msdn.microsoft.com/en-us/library/b0084kay(VS.80).aspx

+7
source share

There is no standard way to do this. It may be possible to highlight specific macros specific to each platform. For example, _WIN32 will be defined on Windows and almost certainly not Linux. However, I do not know any corresponding Linux macro.

Since you use separate compilers, this means that you have separate build environments. Why not just add the macro yourself? Visual Studio and GCC support for defining macros from the command line makes it easy to define them.

+7
source share

I always try to keep the platform specification out of the main code, doing it this way

platform.h:

 #if BUILD_PLATFORM == WINDOWS_BUILD #include "windows_platform.h" #elif BUILD_PLATFORM == LINUX_BUILD #include "linux_platform.h" #else #error UNSUPPORTED PLATFORM #endif 

someclass.c:

 void SomeClass::SomeFunction() { system_related_type t; // Other code platform_SystemCall(&t); // Other code } 

Now in windows_platform.h and linux_platform.h you are typedef system_related_type for the native type and either #define platform_SystemCall as your own call, or create a small wrapper function if the argument set from one platform to another is too different.

If the system APIs for a specific task vary greatly between platforms, you may need to create your own version API that shares the difference. But for the most part, there are fairly direct comparisons between the various APIs on Windows and Linux.

Instead of relying on some specific #define compiler to select a platform, I #define BUILD_PLATFORM in a project file or makefile, since in any case they must be unique by platform.

+5
source share

Here is what I use. It works in Visual Studio 2008 and MinGW:

 #ifdef __GNUC__ #define LINUX #else #define WINDOWS #endif #ifdef WINDOWS #include "stdafx.h" #else #include <stdlib.h> #include <string.h> #include <stdio.h> #include <ctype.h> #include <assert.h> #include <malloc.h> #endif 
0
source share

All Articles