Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

#ifdef _WIN32 not getting detected

Tags:

c++

c++11

I can not get the #ifdef rule to work at least on windows (64 bit). Compiler version is g++ 5.4.0 I have tried:

#ifdef _WIN32
#ifdef _WIN64
#ifdef OS_WINDOWS

I have compiled the following test with: g++ main.cpp

Even with a simple code as this:

#include <iostream>

int main()
{
  std::cout << "you are on...";

  #ifdef _WIN32
  std::cout << "Windows" << std::endl;
  #elif __linux__
  std::cout << "Linux" << std::endl;
  #endif

  return 0;
}

Output is:

"you are on..."

...and nothing else gets couted out.

like image 867
Mikko-Pentti Einari Eronen Avatar asked Jan 11 '17 13:01

Mikko-Pentti Einari Eronen


2 Answers

#ifdef _WIN32
#ifdef _WIN64

These are pre-defined macros defined by the MSVC compiler. You appear to be using g++ instead. That probably means either MinGW, or Cygwin.


Here and here are collections of macros pre-defined by several compilers.

MinGW __MINGW32__

Cygwin __CYGWIN__


If you prefer to not to build hefty ifdef - else trees, and scour the internet for macros defined by obscure compilers, and their different versions, I recommend to instead include a few headers from boost. They have already done the hard part of the work. Although, note that BOOST_OS_WINDOWS is separate from BOOST_OS_CYGWIN.

like image 163
eerorika Avatar answered Oct 24 '22 10:10

eerorika


Use __CYGWIN32__ to detect Windows when compiling g++ in cygwin. (This is defined in both 32 and 64 bit).

_WIN32 &c. may not be defined in that case. It isn't for me.

(As also mentioned in a comment; using echo | g++ -dM -E to output the list of what is defined can be helpful.)

like image 3
Bathsheba Avatar answered Oct 24 '22 12:10

Bathsheba