Home > database >  CMake: How to prevent 64 bit build?
CMake: How to prevent 64 bit build?

Time:03-27

I have a cmake project comprising of two subprojects, say Project 1 and Project 2. Project 1 is an executable and is supposed to be 32 bit. Project 2 is a library (MODULE) and i need both 32 bit and 64 bit versions of it. I am using visual studio 2022. Now, if i select 64 bit (via x64 Release), i am afraid cmake will build 64 bit executable for Project 1. So i want some CMake commands to ensure that Project 1 can be built on 32 bit only. Something like

if(CMAKE_SIZEOF_VOID_P EQUAL 8)
##ABORT##

in Project 1. Thanks

CodePudding user response:

Just emit a fatal error during the cmake configuration.

if(NOT CMAKE_SIZEOF_VOID_P EQUAL 4)
    message(FATAL_ERROR "Project 1 must not be build for 64 bit; choose a configuration using 32 bit")
endif()

Usually you'll want to avoid logic like this in your CMake files though. One of the greatest benefits of CMake is the fact that it usually requires very little effort to compile the binaries of a project for different configurations. If parts of your project only apply to certain configurations, it would be user-friendly to provide a main CMakeLists.txt for the project that makes the appropriate choices without resulting in an error during configuration.

A good way of accompilishing this would be to conditionally add the subdirectory in the parent CMakeLists.txt.

if(CMAKE_SIZEOF_VOID_P EQUAL 4)
    add_subdirectory(project1)
else()
    message("Not a 32 bit build; not adding Project 1")
endif()

add_subdirectory(project2)

Even with this approach you should keep the snippet with the fatal error in the subproject to prevent issues, if some user uses your project in an unintended way and uses Project 1 as source directory instead of your main project dir.

  • Related