cmake config_error ai_generated true

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

Also available as: JSON · Markdown · 中文
88%Fix Rate
86%Confidence
1Evidence
2023-11-20First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
CMake 3.10 active
CMake 3.16 active
CMake 3.20 active
CMake 3.26 active

Root Cause

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

中文

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

Official Documentation

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

Workarounds

  1. 95% success Use a different target name for your executable, e.g., mytarget_exe instead of mytarget. Update all references accordingly. Example: add_executable(mytarget_exe main.cpp) target_link_libraries(mytarget_exe PRIVATE mytarget)
    Use a different target name for your executable, e.g., mytarget_exe instead of mytarget. Update all references accordingly. Example: add_executable(mytarget_exe main.cpp) target_link_libraries(mytarget_exe PRIVATE mytarget)
  2. 75% success Remove the imported target before creating your own: if(TARGET mytarget) add_library(mytarget ALIAS mytarget_import) endif() then create your target with a different name.
    Remove the imported target before creating your own: if(TARGET mytarget) add_library(mytarget ALIAS mytarget_import) endif() then create your target with a different name.
  3. 85% success Use a namespace for the imported target (e.g., find_package(MyPackage) creates MyPackage::mytarget). Then your target can be named mytarget without conflict.
    Use a namespace for the imported target (e.g., find_package(MyPackage) creates MyPackage::mytarget). Then your target can be named mytarget without conflict.

中文步骤

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

Dead Ends

Common approaches that don't work:

  1. 40% fail

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

  2. 80% fail

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

  3. 100% fail

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