Building 32bit applications with mingw-w64 and CMake

The mingw-w64 provides ready-to-use packages with GCC for Windows. The toolchain is by default targeting the 64bit Windows architecture. It is possible to build 32bit binaries by using the -m32 option on the command line.

The toolchain can be easily integrated with CMake, however it gets more complicated when trying to build a 32bit application from CMake. After some trial and error, reading the documentation and debugging the CMake modules, I found out a simple solution that works for me:

    set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -m32")

    project(MyProject ...)


    find_library(gcc_lib libgcc_s_sjlj-1.dll)
    find_library(cpp_lib libstdc++-6.dll)
    find_library(pthread_lib libwinpthread-1.dll)

Some notes:

    • According to the CMake documentation, CMake should set “FIND_LIBRARY_USE_LIB32_PATHS” automatically because MinGW requires it, but as of now (mingw-7.2.0 and CMake 3.12), it is not the case. So set it explicitly. Without this, find_library() will happily find the 64bit version of the libraries in the MinGW installation, causing linker errors.
    • I set CMAKE_C_FLAGS and CMAKE_CXX_FLAGS before the project() statement, because in project(), CMake will look for the compiler and retrieve the library locations by introspection. If the -m32 flag is not used by then, CMake may find and use the location of the 64bit libraries, also causing linker errors later on
This entry was posted in C/C++. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s