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.
Learn the fundamentals of the C++ build process, including the roles of the preprocessor, compiler, and linker.