Writing OS Independent Code in C/C++
How to write a utility program that lists all contents of directory irrespective of Operating System.
Most of the C/C++ compilers, define macros which can be used to detect operating system. For example, in GCC, following are common macros.
_WIN32 : Defined for both 32 bit and 64 bit windows OS. _WIN64 : Defined for 64 bit windows OS. unix, __unix, __unix__ : Defined in UNIX OS __APPLE__, __MACH__ : Defined in Mac OS Source : StackOverflow
In Windows, we us dir call to list all directories and in most of the other Operating Systems “ls” is used. Below is simple C++ implementation to list directories of folder irrespective of OS.
// C++ program to list all directories. #include <bits/stdc++.h> using namespace std; int main() { #ifdef _WIN32 system("dir"); #else system("ls"); #endif return 0; } |
The above OS independent code is totally different from Java’s platform independence. In Java, there is intermediate byte code that is very clean way of handling platform dependencies. Here we have to remember compiler specific macros and write code in using clumsy #ifdef and #else, and the most important, we need to recompile the code for every OS.
This article is contrubuted by Shubham Agrawal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Recommended Posts:
- Writing C/C++ code efficiently in Competitive programming
- Writing first C++ program : Hello World example
- Facts and Question related to Style of writing programs in C/C++
- Self Destructing Code in C
- Basic Code Optimizations in C
- Convert C/C++ program to Preprocessor code
- Code to generate the map of India (with explanation)
- Printing source code of a C program itself
- Code valid in both C and C++ but produce different output
- Convert C/C++ code to assembly language
- How to write a running C code without main()?
- C++: Methods of code shortening in competitive programming
- LEX code to extract HTML tags from a file
- Understanding ShellExecute function and it's application to open a list of URLs present in a file using C++ code
- Code Optimization Technique (logical AND and logical OR)



