- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
#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.
Advertisements