我创建了一个仅标头的库,该库与cmake一起使用
add_library(mylib INTERFACE)
并导出目标。
当我在另一个包含头文件的库(find_package(mylib REQUIRED)
)的cmake文件中使用target_link_library
和mylib2
时,此方法很好用。
但是当我使用导出的目标和mylib2
针对target_link_library
进行链接时,生成的VS文件在链接库中包含mylib.lib
。
当我在所有三个项目的生成文件中寻找字符串mylib.lib
时,只有Visual Studio文件包含此文件,PackageConfig
或PackageTargets
文件中都不包含文件名。
标头库在其CMakeLists.txt中使用导出的目标
add_library(mylib INTERFACE)
target_compile_definitions(mylib INTERFACE -D_USE_MATH_DEFINES)
target_link_libraries(mylib INTERFACE somelibraries)
target_include_directories(mylib INTERFACE
$<INSTALL_INTERFACE:include>
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
)
configure_package_config_file(mylibConfig.cmake.in ${CMAKE_CURRENT_BINARY_DIR}/mylibConfig.cmake INSTALL_DESTINATION ${CMAKE_INSTALL_PREFIX})
install(TARGETS mylib EXPORT mylib-targets)
install(EXPORT mylib-targets FILE mylibTargets.cmake DESTINATION ${CMAKE_INSTALL_PREFIX})
install(FILES ${CMAKE_CURRENT_BINARY_DIR}/mylibConfig.cmake DESTINATION ${CMAKE_INSTALL_PREFIX})
install(DIRECTORY ./ DESTINATION include FILES_MATCHING PATTERN "*.h")
第二个库仅使用
find_package(mylib REQUIRED)
add_library(mylib2 source.cpp)
target_link_libraries(mylib2 mylib)
# some stuff to export targets, similar to the first lib
最终项目使用
add_binary(myproject source.cpp)
set(LINK_LIBRARIES mylib2)
target_link_libraries(myproject ${LINK_LIBRARIES}) # mylib2.lib is added to the project.
add_binary(myproject2 source.cpp)
target_link_libraries(myproject mylib2) # only the include paths are added.
仅当通过变量设置库时才会发生此问题。
在该过程的哪一步,cmake会将库文件名添加到链接库中?它不应该继承INTERFACE
属性吗?
答案 0 :(得分:0)
要包含库,通常必须包含头文件并链接一些目标文件。
话虽如此,如果所说的库是仅标头的,则只需执行include_directories(<library-include-folder>)
就可以了。通常,您的库不应编译为.lib文件。
在您的情况下,您可能需要执行以下操作:(假设mylib仅用于标头)
find_package(mylib REQUIRED)
# Provides MYLIB_INCLUDE_DIR to include
# The line above also provides a MYLIB_LIBRARIES, which for header-only libraries should be empty
include_directories(${MYLIB_INCLUDE_DIR})
add_executable(main main.cpp)
target_link_libraries(main ${MYLIB_LIBRARIES}) # This can be onmitted since there is nothing to link