cmake config_error ai_generated true

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

CMake Error: add_executable cannot create target "mytarget" because an imported target with the same name already exists.

ID: cmake/add-executable-same-name-as-imported-target

其他格式: JSON · Markdown 中文 · English
88%修复率
86%置信度
1证据数
2023-11-20首次发现

版本兼容性

版本状态引入弃用备注
CMake 3.10 active
CMake 3.16 active
CMake 3.20 active
CMake 3.26 active

根因分析

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

English

A previous find_package or add_library call created an IMPORTED target with the same name, or the target is defined in a subdirectory that already imported it.

generic

官方文档

https://cmake.org/cmake/help/latest/command/add_executable.html

解决方案

  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 而不会冲突。

无效尝试

常见但无效的做法:

  1. 40% 失败

    This works but may break downstream dependencies that expect the original target name. Also, the imported target remains unused.

  2. 80% 失败

    If the imported target is needed for linking, removing it causes undefined references.

  3. 100% 失败

    add_library also fails with the same error if the imported target exists.