Writing OS Independent Code in C/C++


A program that can interact with the operating system irrespective of the OS on which it runs.

Most of the compilers of c/c++ have the power to define macros that detect OS.

Some Macros of GCC compiler are −

  • _WIN32: macros for 32 bit and 64-bit Windows OS.

  • _WIN64: macros for 64-bit Windows OS.

  • _UNIX: macros for UNIX OS.

  • _APPLE_: macros for macOS.

Based on these macros defined, let’s create a program that will work irrespective of the OS −

Example

 Live Demo

#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.

Updated on: 17-Apr-2020

255 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements