Home > Backend Development > C++ > body text

Writing OS-independent code in C/C++

王林
Release: 2023-09-09 21:49:02
forward
1167 people have browsed it

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;
}
Copy after login

Output

This lists all files of the directory to the output screen irrespective of OS.
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template