Preprocessor Directives and the Build Process

Using #ifdef for Platform-Specific Code

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

Abstract art representing computer programming

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.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved