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

- **ID:** `cmake/abi-mismatch-pic`
- **领域:** cmake
- **类别:** build_error
- **验证级别:** ai_generated
- **修复率:** 85%

## 根因

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

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| CMake 3.10+ | active | — | — |
| GCC 9.3.0 | active | — | — |

## 解决方案

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

## 无效尝试

- **Add -fPIC manually to target_compile_options for otherlib** — CMake's PIC handling is more nuanced; manual flags may conflict with CMake's own POSITION_INDEPENDENT_CODE property. (60% 失败率)
- **Set CMAKE_POSITION_INDEPENDENT_CODE globally to ON** — Forces PIC on all targets, which may break performance on some architectures (e.g., x86-64) and is not always desired. (40% 失败率)
- **Change mylib to STATIC library to avoid PIC requirement** — If mylib must be shared (e.g., for plugin loading), this changes the library type and may break downstream consumers. (70% 失败率)
