CMake的FindPackage(PythonLibs):库优先级及静态库优先是否符合预期?
FindPackage(PythonLibs) Library Priority and Your Observed Behavior Let's break down your questions one by one:
1. Does FindPythonLibs prefer dynamic or static libraries by default?
Historically, the FindPythonLibs module was designed to prioritize shared (dynamic) libraries like .so (on Linux) over static libraries .a. However, this behavior wasn't always consistent in older CMake versions—there were known bugs (like the 2005 report you referenced) where the module would incorrectly pick static libraries first. Over time, most of these issues were fixed in newer CMake releases, so modern versions of FindPythonLibs should default to dynamic libraries when available.
That said, it's important to note that FindPythonLibs is now considered a legacy module. CMake officially recommends using the newer FindPython3 (or FindPython for cross-version support) modules instead, as they have more predictable behavior and better control over library selection.
2. Why did CMake find python3.5m.a before python3.5m.so?
Even though the default should favor dynamic libraries, there are several reasons you might see static libraries being picked first:
- Modified library search suffixes: If the
CMAKE_FIND_LIBRARY_SUFFIXESvariable was altered (either in your CMakeLists.txt or via environment settings) to list.abefore.so, CMake will prioritize static libraries. You can check this by addingmessage(STATUS "CMAKE_FIND_LIBRARY_SUFFIXES: ${CMAKE_FIND_LIBRARY_SUFFIXES}")to your script. - Dynamic library not in standard paths: The
python3.5m.sofile might be installed in a non-standard directory that CMake doesn't check by default. Even if you know it exists, if it's outside paths like/usr/libor/usr/local/lib, CMake won't find it unless you explicitly add the path withCMAKE_PREFIX_PATHorCMAKE_LIBRARY_PATH. - Older CMake version bug: Since you're working with Python 3.5 (a fairly old release), you might be using a corresponding older CMake version where the
FindPythonLibsmodule still had the static-library-priority bug. Updating CMake to a more recent version (if compatible with your project) could resolve this. - Dynamic library missing or corrupted: It's possible that the
python3.5m.sofile doesn't actually exist in your system, or it's damaged. You can verify this by searching for it withfind / -name "python3.5m.so" 2>/dev/null. - Environment variable issues: If your
LD_LIBRARY_PATH(on Linux) doesn't include the directory containing the dynamic Python library, CMake's find logic might not locate it during the search process.
Glad to hear you already fixed the build by specifying the correct library path—for future reference, switching to FindPython3 would give you more control: you can explicitly request dynamic libraries using Python3_FIND_STATIC_LIBS OFF or static with ON, making the behavior completely predictable.
内容的提问来源于stack exchange,提问作者skincell

