【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即可。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值