How do I check OS with a preprocessor directive?
How do I check OS with a preprocessor directive?
37824-Jul-2023
Updated on 25-Jul-2023
Home / DeveloperSection / Forums / How do I check OS with a preprocessor directive?
How do I check OS with a preprocessor directive?
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
OS
macro will be defined as"Windows"
. If the code is running on Linux, theOS
macro will be defined as"Linux"
. And so on.The
#ifdef
preprocessor directive is used to check if a macro is defined. If the macro is defined, the code between the#ifdef
and#endif
directives will be compiled. Otherwise, the code will be skipped.In this case, the
#ifdef
directive is used to check if the_WIN32
macro 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
#elif
and#else
preprocessor 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