Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect if 64 bit MSVC with cmake?

I have a project which uses cmake, one target is set to only build with MSVC:

 if (MSVC)
     add_library(test SHARED source.cpp) 
 endif()

Now the other issue is that this target is only designed for MSVC 32bit. So how can I detect that the generator is MSVC64 and skip this target?

like image 983
paulm Avatar asked Aug 31 '16 20:08

paulm


Video Answer


4 Answers

The usual way to check if you're generating for a 64 bits architecture is to test CMAKE_SIZEOF_VOID_P:

project( ... )
...

# won't work before project()!    
if(CMAKE_SIZEOF_VOID_P EQUAL 8)
    # 64 bits
elseif(CMAKE_SIZEOF_VOID_P EQUAL 4)
    # 32 bits
endif()

This variable is only set after the project command!

like image 105
rgmt Avatar answered Oct 20 '22 01:10

rgmt


There are several ways - also used by CMake itself - that will check for "not 64Bit":

if(NOT "${CMAKE_GENERATOR}" MATCHES "(Win64|IA64)")
    ...
endif()

if("${CMAKE_SIZEOF_VOID_P}" STREQUAL "4")
    ...
endif()

if(NOT CMAKE_CL_64)
   ...
endif()

References

  • CMAKE_GENERATOR
  • CMAKE_SIZEOF_VOID_P
  • CMAKE_CL_64
like image 36
Florian Avatar answered Oct 20 '22 01:10

Florian


Just encountered a similar issue myself and discovered CMAKE_VS_PLATFORM_NAME, which is calculated based on the generator and I think it's worth a mention.

I've tried it with cmake 3.16.1 (According to the docs it's been available since 3.1.3) using: -GVisual Studio 15 2017, -GVisual Studio 15 2017 Win64 and -GVisual Studio 15 2017 -Ax64 and it was set to: Win32, x64 and x64 respectively. So for this scenario I think checking against Win32 should work e.g.

if ("${CMAKE_VS_PLATFORM_NAME}" STREQUAL "Win32")
    ...
endif ()
like image 2
Chris B Avatar answered Oct 20 '22 01:10

Chris B


On recent versions of CMake/Visual Studio the bitness is selected with CMAKE_GENERATOR_PLATFORM, which can be specified on the command line with -A option:

cmake -G "Visual Studio 16 2019" -A Win32 -DCMAKE_BUILD_TYPE=Release ..

So, based on this feature you can then query the value from within the CMakeLists.txt:

if(NOT ("${CMAKE_GENERATOR_PLATFORM}" STREQUAL "Win64"))
    ...
ENDIF()
like image 4
Dmitry Mikushin Avatar answered Oct 20 '22 01:10

Dmitry Mikushin