CMake新手求助:无法创建"hello-pack"目标,同名目标已存在
Hey there! Let's break down and fix this CMake error you're facing.
What's causing the error?
The problem is straightforward: your main project myapp2 uses add_subdirectory("hello-pack") to include the hello-pack library, but your hello-world-pack also has an add_subdirectory("hello-pack") in its own CMakeLists.txt. CMake treats targets as global entities—so when it tries to create the hello-pack target twice, it throws that "already exists" error.
How to fix it
We'll adjust the dependency structure so hello-pack is only loaded once, and let CMake handle the dependency chain automatically. Here's what to do:
1. Update hello-world-pack's CMakeLists.txt
Open the CMakeLists.txt inside hello-world-pack and remove the line that says add_subdirectory("hello-pack"). Instead, we'll link directly to the existing hello-pack target that the main project has already set up. Your modified file should look something like this:
cmake_minimum_required(VERSION 3.4.1) project("hello-world-pack" C) add_library(hello-world-pack STATIC src/hello-world.c) # Make this library's include directory available to dependent targets target_include_directories(hello-world-pack PUBLIC include) # Link against hello-pack (since we depend on its functionality) target_link_libraries(hello-world-pack PRIVATE hello-pack)
2. Simplify myapp2's CMakeLists.txt
You can clean up the main project's CMake file too—since we're using PUBLIC include directories in the libraries, CMake will automatically pass those include paths to your executable. Update it to:
cmake_minimum_required(VERSION 3.4.1) project("myapp2" C) # Load both libraries (hello-pack only needs to be added once!) add_subdirectory("hello-pack") add_subdirectory("hello-world-pack") add_executable("${PROJECT_NAME}" myapp2.c) # Link the libraries to your executable—CMake handles include paths automatically target_link_libraries("${PROJECT_NAME}" PRIVATE hello-pack hello-world-pack)
Why this works
- CMake targets are global: once
hello-packis added via the main project, it's available to all subdirectories, sohello-world-packcan just reference it directly. - Using
PUBLICintarget_include_directoriestells CMake to pass those include paths along to any target that links againsthello-world-pack—no need to manually addPRIVATEinclude directories in the main project.
This setup properly simulates a scenario where your main app shares a common library with one of its dependencies, without duplicating target definitions.
内容的提问来源于stack exchange,提问作者Anurag Vohra

