cmake build_error ai_generated true

CMake 错误:目标 'mylib' 要求 PIC 模式,但其依赖 'otherlib' 未使用 PIC 构建。请使用 CMAKE_POSITION_INDEPENDENT_CODE=ON 重新配置 otherlib。

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

其他格式: JSON · Markdown 中文 · English
85%修复率
82%置信度
1证据数
2024-05-10首次发现

版本兼容性

版本状态引入弃用备注
CMake 3.10+ active
GCC 9.3.0 active

根因分析

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

English

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

官方文档

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

解决方案

  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 重新构建。

无效尝试

常见但无效的做法:

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

    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% 失败

    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% 失败

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