# CMake 错误：add_executable 无法创建目标 "mytarget"，因为同名导入目标已存在。

- **ID:** `cmake/add-executable-same-name-as-imported-target`
- **领域:** cmake
- **类别:** config_error
- **验证级别:** ai_generated
- **修复率:** 88%

## 根因

之前的 find_package 或 add_library 调用创建了同名导入目标，或者该目标已在子目录中定义并导入。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| CMake 3.10 | active | — | — |
| CMake 3.16 | active | — | — |
| CMake 3.20 | active | — | — |
| CMake 3.26 | active | — | — |

## 解决方案

1. ```
   为可执行文件使用不同的目标名称，例如 mytarget_exe 代替 mytarget。相应更新所有引用。例如：add_executable(mytarget_exe main.cpp) target_link_libraries(mytarget_exe PRIVATE mytarget)
   ```
2. ```
   在创建自己的目标之前移除导入目标：if(TARGET mytarget) add_library(mytarget ALIAS mytarget_import) endif() 然后使用不同的名称创建目标。
   ```
3. ```
   为导入目标使用命名空间（例如 find_package(MyPackage) 创建 MyPackage::mytarget）。那么你的目标可以命名为 mytarget 而不会冲突。
   ```

## 无效尝试

- **** — This works but may break downstream dependencies that expect the original target name. Also, the imported target remains unused. (40% 失败率)
- **** — If the imported target is needed for linking, removing it causes undefined references. (80% 失败率)
- **** — add_library also fails with the same error if the imported target exists. (100% 失败率)
