cmake build_error ai_generated true

CMake Error: Target 'mylib' requires PIC mode but its dependency 'otherlib' is built without PIC. Reconfigure otherlib with CMAKE_POSITION_INDEPENDENT_CODE=ON.

ID: cmake/abi-mismatch-pic

Also available as: JSON · Markdown · 中文
85%Fix Rate
82%Confidence
1Evidence
2024-05-10First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
CMake 3.10+ active
GCC 9.3.0 active

Root Cause

A shared library target requires position-independent code (PIC), but a static library dependency was built without PIC, causing linker errors or ABI incompatibility.

generic

中文

共享库目标需要位置无关代码 (PIC),但静态库依赖项未使用 PIC 构建,导致链接错误或 ABI 不兼容。

Official Documentation

https://cmake.org/cmake/help/latest/variable/CMAKE_POSITION_INDEPENDENT_CODE.html

Workarounds

  1. 95% success Set PIC on the dependency target explicitly: set_target_properties(otherlib PROPERTIES POSITION_INDEPENDENT_CODE ON). Then reconfigure.
    Set PIC on the dependency target explicitly: set_target_properties(otherlib PROPERTIES POSITION_INDEPENDENT_CODE ON). Then reconfigure.
  2. 90% success In CMakeLists.txt, before add_library for otherlib, set: set(CMAKE_POSITION_INDEPENDENT_CODE ON). This ensures all subsequent static libraries are built with PIC.
    In CMakeLists.txt, before add_library for otherlib, set: set(CMAKE_POSITION_INDEPENDENT_CODE ON). This ensures all subsequent static libraries are built with PIC.
  3. 85% success If otherlib is an external package, rebuild it with -DCMAKE_POSITION_INDEPENDENT_CODE=ON flag during its own CMake configure step.
    If otherlib is an external package, rebuild it with -DCMAKE_POSITION_INDEPENDENT_CODE=ON flag during its own CMake configure step.

中文步骤

  1. 在依赖目标上显式设置 PIC:set_target_properties(otherlib PROPERTIES POSITION_INDEPENDENT_CODE ON)。然后重新配置。
  2. 在 CMakeLists.txt 中,在 add_library 为 otherlib 之前设置:set(CMAKE_POSITION_INDEPENDENT_CODE ON)。确保后续所有静态库都使用 PIC 构建。
  3. 如果 otherlib 是外部包,在其自己的 CMake 配置步骤中使用 -DCMAKE_POSITION_INDEPENDENT_CODE=ON 重新构建。

Dead Ends

Common approaches that don't work:

  1. Add -fPIC manually to target_compile_options for otherlib 60% fail

    CMake's PIC handling is more nuanced; manual flags may conflict with CMake's own POSITION_INDEPENDENT_CODE property.

  2. Set CMAKE_POSITION_INDEPENDENT_CODE globally to ON 40% fail

    Forces PIC on all targets, which may break performance on some architectures (e.g., x86-64) and is not always desired.

  3. Change mylib to STATIC library to avoid PIC requirement 70% fail

    If mylib must be shared (e.g., for plugin loading), this changes the library type and may break downstream consumers.