Is there any way to autodetect your Operating System using your C/C++ code? I need this for running some crossplatform code for Linux, Windows, even on a Raspberry Pi. I am trying to autodetect the OS so that I am not put in the situation that I have to ask for the OS that is running on the machine as an input.
I was thinking about a hack like verifying the file system structure or something like that, I don't know if I am on to something or not.
I have used below code in past for checking between linux and windows
#include<stdio.h>
int main(int argc, char *argv[])
{
#ifdef _WIN32
printf("in Windows");
#endif
#ifdef linux
printf("In Linux");
#endif
return 0;
}
Usually all toolchain has their own predefined macros so you need to use those macros to detect which os is this.
List of such predefined macros.
http://sourceforge.net/p/predef/wiki/OperatingSystems/
Yes as a side note, Here detection of OS is happened using compile time macros. So according to toolchain respective macro's defination will go in build.
To detect OS version in runtime, like in java we do
System.getProperty("os.name")
Same way in C/C++ we do not have any API.
In POSIX systems using 'uname' we can get OS name.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With