Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autodetection of OS in C/C++

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.

like image 537
123123d Avatar asked Dec 08 '15 09:12

123123d


1 Answers

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.

like image 173
Jeegar Patel Avatar answered Sep 29 '22 02:09

Jeegar Patel