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

CMake项目间add_dependencies使用问题:生成文件依赖无法解析求助

Fixing CMake Dependency Issue with Generated Source File xyz_made.cpp

Let's tackle this problem directly. The core issue here is that CMake checks for the existence of all listed source files during the configuration phase, but your xyz_made.cpp isn't generated until the build phase by the xyz project. Even though you added add_dependencies, that only ensures xyz builds before abc—it doesn't stop CMake from throwing an error when it can't find the generated file upfront.

Here's how to fix it step by step:

1. Mark the Generated File as GENERATED

Tell CMake explicitly that xyz_made.cpp is a build-time generated file, so it skips the existence check during configuration. Add this line before defining your library:

set_source_files_properties(${xyz_BIN_DIR}/xyz_made.cpp PROPERTIES GENERATED TRUE)

2. Verify the Generated File Path

Double-check that ${xyz_BIN_DIR} correctly points to the directory where xyz actually outputs xyz_made.cpp. If xyz uses add_custom_command or add_custom_target to generate the file, make sure its OUTPUT path matches what you're referencing in abc's CMakeLists.txt.

3. (Optional) Replace AUX_SOURCE_DIRECTORY for Better Control

While not strictly required for fixing the dependency issue, AUX_SOURCE_DIRECTORY can lead to unexpected behavior (it auto-collects all source files in a directory, including any temporary or unwanted files). It's better to manually list your source files for clarity:

# Replace AUX_SOURCE_DIRECTORY with explicit source file list
set(source
    src/file1.cpp
    src/file2.cpp
    # Add all your non-generated source files here
)

Modified CMakeLists.txt Example

Putting it all together, your updated config should look like this:

include_directories(${CMAKE_CURRENT_SOURCE_DIR})

# Explicit source file list (recommended over AUX_SOURCE_DIRECTORY)
set(source
    your_main_source.cpp
    # Add other non-generated source files here
)

project(abc)

# Mark the generated file so CMake doesn't check for it during configuration
set_source_files_properties(${xyz_BIN_DIR}/xyz_made.cpp PROPERTIES GENERATED TRUE)

add_library(${PROJECT_NAME} STATIC ${source} ${xyz_BIN_DIR}/xyz_made.cpp )
add_dependencies(${PROJECT_NAME} xyz)
target_link_libraries(${PROJECT_NAME} PRIVATE xyz )
target_include_directories(${PROJECT_NAME} PRIVATE ${xyz_SOURCE_DIR} )

# Installation
install(TARGETS ${PROJECT_NAME} DESTINATION ${DST_LIB_DIR})

Why This Works

By setting the GENERATED property, CMake understands that the file will exist by the time the build phase runs. Combined with add_dependencies(${PROJECT_NAME} xyz), this guarantees that xyz completes its build (and generates xyz_made.cpp) before abc starts compiling.

内容的提问来源于stack exchange,提问作者badri

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:09:17