You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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-pack is added via the main project, it's available to all subdirectories, so hello-world-pack can just reference it directly.
  • Using PUBLIC in target_include_directories tells CMake to pass those include paths along to any target that links against hello-world-pack—no need to manually add PRIVATE include 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:30:15