Home > Article > Backend Development > Writing OS-independent code in C/C++
A program that can interact with the operating system, regardless of which operating system it is running on.
Most c/c compilers have the ability to define macros to detect the operating system.
Some GCC compiler macros include:
_WIN32: Macros for 32-bit and 64-bit Windows operating systems.
_WIN64: Macro for 64-bit Windows operating systems.
_UNIX: Macro for UNIX operating system.
_APPLE_: macOS macro.
Based on these defined macros, let’s create a program that is not restricted by the operating system:
Live demonstration
#include <iostream> using namespace std; int main() { #ifdef _WIN32 system("dir"); #else system("ls"); #endif return 0; }
This lists all files of the directory to the output screen irrespective of OS.
The above is the detailed content of Writing OS-independent code in C/C++. For more information, please follow other related articles on the PHP Chinese website!