How do I check OS with a preprocessor directive?
How do I check OS with a preprocessor directive?
733
24-Jul-2023
Updated on 25-Jul-2023
Aryan Kumar
25-Jul-2023Sure, I can help you with that.
Here is how you can check the operating system in C using preprocessor directives:
C
This code first includes the
<stdio.h>header file, which provides theprintf()function. Then, it defines a preprocessor macro calledOS. The value of this macro will be different depending on the operating system that the code is running on.For example, if the code is running on Windows, the
OSmacro will be defined as"Windows". If the code is running on Linux, theOSmacro will be defined as"Linux". And so on.The
#ifdefpreprocessor directive is used to check if a macro is defined. If the macro is defined, the code between the#ifdefand#endifdirectives will be compiled. Otherwise, the code will be skipped.In this case, the
#ifdefdirective is used to check if the_WIN32macro is defined. If it is, the code will compile and print the string "Windows" to the console. If it is not, the code will compile and print the string "Unknown" to the console.You can also use the
#elifand#elsepreprocessor directives to check for other operating systems. For example, the following code will print the string "Linux" if the code is running on Linux, and the string "Unknown" if it is running on any other operating system:C