OS auto-detection in C / C ++

Is there a way to auto-detect your operating system using C / C ++ code? I need this to run cross-platform code for Linux, Windows, even on a raspberry Pi. I am trying to autodetect the OS, so I did not put in a situation that I should ask for the OS running on the computer as input.

I was thinking of hacking, like checking the structure of a file system or something like that, I don't know if I find something or not.

+5
source share
2 answers

I used below code in the past to check 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 the entire toolchain has its own predefined macros, so you need to use these macros to determine which one is this.

A list of such predefined macros.

http://sourceforge.net/p/predef/wiki/OperatingSystems/


Yes, as a side note. Here OS detection occurs using compile-time macros. So, according to the toolchain, the corresponding macro definition will go in the assembly.

To detect the OS version at runtime , as in java, we do

 System.getProperty("os.name") 

The same thing in C / C ++ we do not have an API.


On POSIX systems using uname 'we can get the OS name.

+6
source

There is this convenient list (save it to disk!). A list of predefined compiler macros .

I would also suggest that if you are targeting multiple platforms, find a library that is already available to them.

+4
source

Source: https://habr.com/ru/post/1237638/


All Articles