How can i detect Windows or Linux in C,C++ programming?

By -


Sometimes we need to write platform independent  code which works in windows and linux machine without giving any flag or any modification in code or make file manually.

So in such case i usually use compiler generated macro to check the platform .


In Linux all c and c++ compiler define macro like  linux, In Windows all c and c++ compiler define macro like _WIN32 

so we can use this macro to separate code for linux and windows see belows example code

int main(int argc, char *argv[])
#ifdef _WIN32
   printf("in Windows");
#ifdef linux
    printf("In Linux");
    return 0;

Now compile this code and run On linux it will print In Linux and on windows it will print in Windows.

hey I am an Artist who love to write code...! Well I am an EC graduate From Ganpat University and now i am working as Embedded software engineer in one private firm.. find me at here Jeegar Patel

Leave a Reply

Your email address will not be published. Required fields are marked *