Using #ifdef for Platform-Specific Code

How can I use #ifdef to write platform-specific code in C++?

You can use #ifdef along with platform-specific macros to conditionally compile code for different platforms. Here's an example:

#include <iostream>

#ifdef _WIN32  
#include <windows.h>
void PlatformSpecificFunction() {
  // Windows-specific code
  std::cout << "Running on Windows\n";
}

#elif defined(__APPLE__)  
#include <CoreFoundation/CoreFoundation.h>
void PlatformSpecificFunction() {
  // macOS-specific code
  std::cout << "Running on macOS\n";
}

#elif defined(__linux__)  
#include <unistd.h>
void PlatformSpecificFunction() {
  // Linux-specific code
  std::cout << "Running on Linux\n";
}

#else
#error "Unsupported platform"
#endif

int main() {
  PlatformSpecificFunction();
}
Running on Windows

In this example:

  • #ifdef _WIN32 checks if the code is being compiled for Windows.
  • #elif defined(__APPLE__) checks if the code is being compiled for macOS.
  • #elif defined(__linux__) checks if the code is being compiled for Linux.
  • #else block handles unsupported platforms and raises a compilation error with #error.

By using platform-specific macros and #ifdef, you can include platform-specific headers, define platform-specific functions, and write code tailored for different operating systems.

Note: The exact macros and headers used may vary depending on the compiler and platform. Consult your compiler's documentation for the appropriate macros to use.

Preprocessor Directives and the Build Process

Learn the fundamentals of the C++ build process, including the roles of the preprocessor, compiler, and linker.

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Defining Macros with Arguments
How can I define a macro that takes arguments in C++?
#ifdef vs #if defined()
What is the difference between #ifdef and #if defined() in C++?
Preventing Multiple Header Inclusion
What are the best practices to prevent multiple inclusion of header files?
Defining Constants with #define
Should I use #define to define constants in C++?
Using #pragma once in Header Files
What are the advantages of using #pragma once in header files?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant