cmake
build_error
ai_generated
true
CMake Error: add_library cannot create target "mylib" because another target with the same name already exists.
ID: cmake/target-already-exists
85%Fix Rate
88%Confidence
1Evidence
2024-03-15First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| cmake 3.22 | active | — | — | — |
| cmake 3.28 | active | — | — | — |
| cmake 3.30 | active | — | — | — |
Root Cause
A target with the same name is defined twice in the same directory scope, typically due to duplicate add_library or add_executable calls, or a misspelled target name in a subdirectory.
generic中文
在同一目录范围内重复定义了同名目标,通常是由于重复的 add_library 或 add_executable 调用,或子目录中目标名称拼写错误。
Official Documentation
https://cmake.org/cmake/help/latest/command/add_library.htmlWorkarounds
-
85% success 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.
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.
-
95% success 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()
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()
中文步骤
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.
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()
Dead Ends
Common approaches that don't work:
-
60% fail
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.
-
90% fail
The error is in CMakeLists.txt logic, not cached state; clearing cache does not fix duplicate target definitions.
-
100% fail
target_compile_definitions does not create or rename targets; it only adds compile definitions to existing targets.