Programming Tips - C/C++: Conditional compile by OS (Windows or Linux)

Date: 2020apr24 Update: 2026sep23 Language: C/C++ Q. C/C++: Conditional compile by OS (Windows or Linux) A. Use predefined macros like this:
#ifdef __linux__ // We are compiling on Linux #elif defined(_WIN32) || defined(_WIN64) // We are compiling on Windows #else // Not windows or Linux! #endif
Here's an example use:
char getNativeSlash() { #if defined(_WIN32) || defined(_WIN64) return '\\'; #else return '/'; #endif }
Or that could be done:
#if defined(_WIN32) || defined(_WIN64) const char gNativeSlash = '\\'; #else const char gNativeSlash = '/'; #endif
Full Example:
#include <stdio.h> char getNativeSlash() { #if defined(_WIN32) || defined(_WIN64) return '\\'; #else return '/'; #endif } int main() { printf("The native slash is %c\n", getNativeSlash()); }
Output (On Linux):
The native slash is /