# CMake 错误：add_library 无法创建目标 "mylib"，因为已存在同名目标。

- **ID:** `cmake/target-already-exists`
- **领域:** cmake
- **类别:** build_error
- **验证级别:** ai_generated
- **修复率:** 85%

## 根因

在同一目录范围内重复定义了同名目标，通常是由于重复的 add_library 或 add_executable 调用，或子目录中目标名称拼写错误。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| cmake 3.22 | active | — | — |
| cmake 3.28 | active | — | — |
| cmake 3.30 | active | — | — |

## 解决方案

1. ```
   Ensure each target has a unique name across all subdirectories. Use `add_library(mylib STATIC src/mylib.cpp)` only once. If needed, use `set_target_properties` to alias or create an INTERFACE library with a different name.
   ```
2. ```
   If the duplicate is intentional (e.g., from FetchContent), wrap in `if(NOT TARGET mylib)` before definition:
if(NOT TARGET mylib)
  add_library(mylib STATIC src/mylib.cpp)
endif()
   ```

## 无效尝试

- **** — The real cause is a duplicate definition; renaming may hide the issue but the original duplicate remains, causing other targets to reference the wrong one. (60% 失败率)
- **** — The error is in CMakeLists.txt logic, not cached state; clearing cache does not fix duplicate target definitions. (90% 失败率)
- **** — target_compile_definitions does not create or rename targets; it only adds compile definitions to existing targets. (100% 失败率)
