一个项目A依赖共享库B,B依赖C,A不依赖C,为什么我需要A的CMakelist.txt中的find_package和targe_link C?

时间:2019-08-26 15:08:13

标签: cmake

一个项目A依赖于共享库B,B依赖于第三方库C,A不依赖于C,为什么我需要在A的CMakelist.txt中找到find_package C?第三方库C是PCL。

共享库B的CMakelist.txt。

add_library(TdLib SHARED
        pcl_tools.cpp
        pcl_tools.h
        )

#PCL
find_package(PCL 1.8 REQUIRED)
include_directories(${PCL_INCLUDE_DIRS})
link_directories(${PCL_LIBRARY_DIRS})

set(HEADER_FILES
        pcl_tools.h
        )
set_target_properties(TdLib PROPERTIES
        PUBLIC_HEADER
        "${HEADER_FILES}"
        )

target_link_libraries(TdLib
                    ${PCL_LIBRARIES}
                    )

install(TARGETS TdLib
        # IMPORTANT: Add the foo library to the "export-set"
        EXPORT ${PROJECT_NAME}Targets
        RUNTIME DESTINATION "${INSTALL_BIN_DIR}" COMPONENT bin
        LIBRARY DESTINATION "${INSTALL_LIB_DIR}" COMPONENT shlib
        PUBLIC_HEADER DESTINATION "${INSTALL_INCLUDE_DIR}/TdLibrary"
        COMPONENT dev)

我通过安装B

cmake .. -DCMAKE_INSTALL_PREFIX:=/home/wang/CLionProjects/TdLibrary/install
make
make install

项目A的CMakelist.txt。

cmake_minimum_required(VERSION 3.9)
project(Test)
set(CMAKE_CXX_STANDARD 11)

#TdLib
set(TdLib_DIR "/home/wang/CLionProjects/TdLibrary/install/lib/CMake/TdLib/")
find_package(TdLib REQUIRED)
include_directories(${TdLib_INCLUDE_DIRS})
MESSAGE(STATUS "TdLib_INCLUDE_DIRS = " ${TdLib_INCLUDE_DIRS})

#PCL
find_package(PCL 1.8 REQUIRED)
include_directories(${PCL_INCLUDE_DIRS})
link_directories(${PCL_LIBRARY_DIRS})

add_executable(openMpTest main.cpp)
target_link_libraries(openMpTest
        ${TdLib_LIBRARIES}
        )

如果我注释代码find_package(PCL 1.8 REQUIRED), 错误将发生如下:

Scanning dependencies of target openMpTest
[ 50%] Building CXX object CMakeFiles/Test.dir/main.cpp.o
[100%] Linking CXX executable Test
/usr/bin/ld: Cannot find -lvtkChartsCore
/usr/bin/ld: Cannot find -lvtkCommonColor
/usr/bin/ld: Cannot find -lvtkCommonDataModel
...
...
collect2: error: ld returned 1 exit status
CMakeFiles/Test.dir/build.make:117: recipe for target 'Test' failed
make[2]: *** [Test] Error 1
CMakeFiles/Makefile2:72: recipe for target 'CMakeFiles/Test.dir/all' failed
make[1]: *** [CMakeFiles/Test.dir/all] Error 2
Makefile:83: recipe for target 'all' failed
make: *** [all] Error 2

1 个答案:

答案 0 :(得分:1)

对B的CMakelist.txt的修改:

target_link_libraries(TdLib PRIVATE
                    ${PCL_LIBRARIES}
                    )

PRIVATE选项表示依赖项仅由B使用。依赖B的A不需要find_package(C)。