Static Python on Windows / Find_Python

While modernizing some CMake projects, I tried switching to the Find_Python modules, and all seemed well until I tried running the Windows exe on a test machine, and then it can’t find PythonX.dll.

This makes sense: Despite specifying (Python_USE_STATIC_LIBS ON) for the correct Python prefix, Find_Python/Support.cmake has the following:

  unset (_${_PYTHON_PREFIX}_CMAKE_FIND_LIBRARY_SUFFIXES)
  if (DEFINED ${_PYTHON_PREFIX}_USE_STATIC_LIBS AND NOT WIN32)
    set(_${_PYTHON_PREFIX}_CMAKE_FIND_LIBRARY_SUFFIXES ${CMAKE_FIND_LIBRARY_SUFFIXES})
    if(${_PYTHON_PREFIX}_USE_STATIC_LIBS)
      set (CMAKE_FIND_LIBRARY_SUFFIXES ${CMAKE_STATIC_LIBRARY_SUFFIX})
    else()
      list (REMOVE_ITEM CMAKE_FIND_LIBRARY_SUFFIXES ${CMAKE_STATIC_LIBRARY_SUFFIX})
    endif()
  endif()

Is there a reason Win32 can’t statically link Python?

CMAKE_MINIMUM_REQUIRED(VERSION 3.18)
PROJECT(Test)
SET(Python_USE_STATIC_LIBS ON)
FIND_PACKAGE(Python REQUIRED COMPONENTS Development.embed)
IF (_Python_LIBRARY_TYPE STREQUAL "SHARED")
  MESSAGE(FATAL_ERROR "shared python selected.")  # Fails on windows
ENDIF()

Do you have a static build of Python? Where are you getting your Python from?

Note that static Python is generally much harder to use (unless you’re OK sticking with the standard library and pure Python modules as modules requiring compilation need code to inject into the static build’s lookup tables).

As far as I know, there is no static version of python from any Python distributions available on Windows. This is why the hint Python_USE_STATIC_LIBS is ignored on this platform.

We’re embedding python for scripting automation with a policy of no external dependencies. After experimenting with trying to build a static Python3 on Windows, and seeing the hoops others have had to jump through to try and pull it off, I see why there isn’t one … but that still makes it frustrating to have the flag simply ignored like this.

IMO, emitting a warning when a flag is swallowed would be an improvement.

1 Like

Feel free to create an issue about that on the bug tracker (I don’t have the bandwidth for CMake stuff until a couple of weeks):

https://gitlab.kitware.com/cmake/cmake/-/issues

Done Python_USE_STATIC_LIBS swallowed without warning on Windows (#22956) · Issues · CMake / CMake · GitLab (kitware.com)