CMake项目间add_dependencies使用问题:生成文件依赖无法解析求助
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

