CMake 错误:install(EXPORT) 生成了目标 "mylib",但目标 "mylib" 的库输出路径 "/build/lib" 与安装目标 "/usr/local/lib" 不匹配
CMake Error: install(EXPORT) generated target "mylib" but target "mylib" has library output path "/build/lib" that does not match the install destination "/usr/local/lib"
ID: cmake/export-library-path-mismatch
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| cmake 3.26.0 | active | — | — | — |
| cmake 3.27.0 | active | — | — | — |
| cmake 3.28.0 | active | — | — | — |
根因分析
目标的 LIBRARY_OUTPUT_DIRECTORY 或 ARCHIVE_OUTPUT_DIRECTORY 与 install(TARGETS) 中指定的 DESTINATION 不同,导致 CMake 在生成导出时检测到不匹配。
English
The target's LIBRARY_OUTPUT_DIRECTORY or ARCHIVE_OUTPUT_DIRECTORY differs from the DESTINATION specified in install(TARGETS), causing CMake to detect a mismatch during export generation.
官方文档
https://cmake.org/cmake/help/latest/command/install.html#exporting-targets解决方案
-
使用生成器表达式将目标的输出目录设置为与安装目标匹配: set_target_properties(mylib PROPERTIES LIBRARY_OUTPUT_DIRECTORY "${CMAKE_INSTALL_PREFIX}/lib" ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_INSTALL_PREFIX}/lib" ) 然后确保 install(TARGETS mylib DESTINATION lib) 匹配。 -
使用与构建输出匹配的 install(DESTINATION) 相对路径: set_target_properties(mylib PROPERTIES LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib") install(TARGETS mylib DESTINATION "${CMAKE_BINARY_DIR}/lib") 然后使用 install(EXPORT ... DESTINATION "${CMAKE_BINARY_DIR}/lib") 生成导出。
无效尝试
常见但无效的做法:
-
Change LIBRARY_OUTPUT_DIRECTORY to match the install destination
60% 失败
LIBRARY_OUTPUT_DIRECTORY affects build-time output, not install; changing it may break build scripts or tests that expect the library in the original build directory.
-
Remove install(EXPORT) entirely
90% 失败
Removes the export mechanism, so downstream projects using find_package will fail to locate the package.