Home  >  Article  >  Backend Development  >  Writing OS-independent code in C/C++

Writing OS-independent code in C/C++

王林
王林forward
2023-09-09 21:49:021168browse

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:

Example

Live demonstration

#include <iostream>
using namespace std;
int main() {
   #ifdef _WIN32
      system("dir");
   #else
      system("ls");
   #endif
      return 0;
}

Output

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete