【Cmake】在cmakelist中将头文件(没有对应源文件)链接上所需的库的步骤

前言

有时候,我们会将函数声明和函数定义不分开写,直接写在一个头文件中,那么,如果该头文件需要链接其他手写的库函数时,该怎么写呢?我们知道cpp文件是很好链接的,例如,我要给nominal_path_smoother.cpp文件链接上该文件调用的voy::adv_geom库相关的函数,那么cmakeList中可以这么写:

add_library(voy_planner_behavior_util_nominal_path_smoother
  nominal_path_smoother.cpp
)

target_link_libraries(voy_planner_behavior_util_nominal_path_smoother
  PRIVATE
    voy::adv_geom
)

如果,此时我有一个nominal_path_searcher.h文件(没有对应的nominal_path_searcher.cpp)也需要链接上该文件调用的voy::adv_geom库相关的函数,依旧上面的方式写的话:

add_library(voy_planner_behavior_util_nominal_path_smoother
  nominal_path_searcher.h
)

target_link_libraries(voy_planner_behavior_util_nominal_path_smoother
  PRIVATE
    voy::adv_geom
)

是无法正确链接成功的,会依旧提示找不到adv_geom库。具体链接方式应该如下:

使用Interface library来链接

我们假设INTERFACE 名字为voy_planner_behavior_util_interface,Cmakelist和nominal_path_searcher.h文件是在同一级目录下,那么正确的链接步骤如下:

add_library(voy_planner_behavior_util_interface INTERFACE)

# Add the path to the directory containing nominal_path_searcher.h
target_include_directories(voy_planner_behavior_util_interface
  INTERFACE
    # ${PROJECT_SOURCE_DIR}/path/to/nominal_path_searcher_directory
    ${PROJECT_SOURCE_DIR}/../
)

# Link the trace provider library
target_link_libraries(voy_planner_behavior_util_interface
  INTERFACE
    voy::adv_geom
)

另外,还需要在用到了nominal_path_searcher.h文件的地方引用voy_planner_behavior_util_interface

target_link_libraries(your_target_name
  PRIVATE
    voy_planner_behavior_util_interface
)

例如,在voy_planner_utility_pathpath_costing.cpp中调用了nominal_path_searcher.h文件,那么

add_library(voy_planner_utility_path
  path_costing.cpp
)
target_link_libraries(voy_planner_utility_path
  PUBLIC
    voy_planner_behavior_util_interface

至于使用PUBLIC还是PRIVATE,有一个原则:如果nominal_path_searcher.h是被path_costing.cpp的头文件path_costing.hinclude,那么target_link_libraries时就用PUBLIC;相反,如果直接在path_costing.cpp包含nominal_path_searcher.h,使用PRIVATE即可。

猜你喜欢

转载自blog.csdn.net/qq_40145095/article/details/132150088
今日推荐