[Cmake] Steps to link header files (without corresponding source files) to the required libraries in cmakelist

Preface

Sometimes, we will write the function declaration and function definition directly in a header file instead of separately. So, if the header file needs to link to other hand-written library functions, how should it be written? We know that cpp files are easy to link. For example, if I want to link the file to the library-related functions nominal_path_smoother.cppcalled by the file , then I can write this in cmakeList:voy::adv_geom

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
)

If, at this time, I have a nominal_path_searcher.hfile (no corresponding one ) and need to link to the library-related functions nominal_path_searcher.cppcalled by the file , I still write it in the above way: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
)

It cannot be successfully linked correctly, and it will still prompt that adv_geomthe library cannot be found. The specific link method should be as follows:

Use the Interface library to link

We assume that the INTERFACE name is voy_planner_behavior_util_interface, Cmakelist and nominal_path_searcher.hthe file are in the same directory, then the correct link steps are as follows:

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.hIn addition, you also need to quote where the file is used.voy_planner_behavior_util_interface

target_link_libraries(your_target_name
  PRIVATE
    voy_planner_behavior_util_interface
)

For example, if a file is called voy_planner_utility_pathinpath_costing.cppnominal_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

PUBLICAs for usage PRIVATE, there is a principle: if nominal_path_searcher.hit is included in path_costing.cppthe header file , then use it ; on the contrary, if it is included directly , just use it.path_costing.hincludetarget_link_librariesPUBLICpath_costing.cppnominal_path_searcher.hPRIVATE

Guess you like

Origin blog.csdn.net/qq_40145095/article/details/132150088