前言
有时候,我们会将函数声明和函数定义不分开写,直接写在一个头文件中,那么,如果该头文件需要链接其他手写的库函数时,该怎么写呢?我们知道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_path
的path_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.h
所include
,那么target_link_libraries
时就用PUBLIC
;相反,如果直接在path_costing.cpp
包含nominal_path_searcher.h
,使用PRIVATE
即可。