Windows 32-bit binaries with CMake + MSVC

Certain program and drivers on Windows require 32-bit binaries. Perhaps the source code for the program or driver is lost or otherwise not available, and reverse engineering is not an option. Or perhaps an embedded Windows system requires a 32-bit binary. CMake and MSVC can easily build 32-bit binaries on 64-bit Windows. It’s also possible to cross-compile 32-bit binaries on 64-bit Linux or Windows using MinGW, but this article focuses solely on MSVC.

The “Visual Studio” CMake generator is necessary with CMake architecture specified as “Win32”. Using non-Visual Studio CMake generators like Ninja require a cross-compiler CMake toolchain or using the 32-bit native Visual Studio prompt. To avoid these complications, this example uses the Visual Studio CMake generator. This can be done from the command line like:

cmake -G "Visual Studio 17 2022" -A Win32 -B build
cmake --build build

This can be turned into a one-step workflow using a CMakePresets.json like:

{
  "version": 6,
  "cmakeMinimumRequired": {
    "major": 3,
    "minor": 25,
    "patch": 0
  },
  "configurePresets": [
    {
      "name": "default",
      "generator": "Visual Studio 17 2022",
      "architecture": "Win32",
      "binaryDir": "${sourceDir}/build"
    }
  ],
    "buildPresets": [
        {
        "name": "default",
        "configurePreset": "default",
        "configuration": "Release"
        }
      ],
"workflowPresets": [
  {
    "name": "default",
    "steps": [
      {
        "type": "configure",
        "name": "default"
      },
      {
        "type": "build",
        "name": "default"
      }
    ]
  }
]
}

and then build with:

cmake --workflow --preset default

DLL building

Regardless of 32-bit or 64-bit binaries, if a DLL is required to be built, use the add_library(... SHARED ...) command in the CMakeLists.txt file.