【CMake】target_include_directories和include_directories

最近做项目遇到了一个问题,一个功能包里有两个节点文件,A节点依赖于Opencv3,B节点依赖于Opencv4,想让两个节点分别找到对应版本的OpenCV,这时候就要对CMakeLists.txt做一些改动。

使用target_include_directories替换include_directories,这篇博客很好的解决了我的问题,这里转载一下,表示感谢:

版权声明:本文转载自CSDN博主「夜空紫色」的原创文章
原文链接:https://blog.csdn.net/qq_33726635/article/details/121896441

1.作用

给源文件添加头文件搜索路径:将指定目录添加到编译器的头文件搜索路径之下,指定的目录被解释成当前源码路径的相对路径

2.区别:

2.1 include_directories:

当前CMakeList.txt中的所有目标以及所有在其调用点之后添加的子目录中的所有目标将具有此头文件搜索路径。

2.2 target_include_directories:

指定目标包含的头文件路径。

3.用法

3.1 include_directories([AFTER|BEFORE] [SYSTEM] dir1 [dir2 …])

例: include_directories(/usr1/dirs)

3.2 target_include_directories(\ [SYSTEM] [AFTER|BEFORE] [items1…])

例: target_include_directories(target_so PUBLIC /usr1/dirs)

3.3 使用依据:

INTERFACE:target对应的头文件使用
PRIVATE:target对应的源文件使用
PUBLIC:target对应的头文件、源文件都使用

4 应用实例

节点A的CMakeList.txt

1
2
3
4
5
6
7
8
9
10
11
# OpenCV 3
find_package(OpenCV 3 REQUIRED)
aux_source_directory(. DIR_SRCS)
add_library(myTagLib SHARED ${DIR_SRCS})
target_include_directories(myTagLib
PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include/tag_detector
PUBLIC ${OpenCV_INCLUDE_DIRS}
)
target_link_libraries(myTagLib
${OpenCV_LIBS}
)

节点B的CMakeList.txt

1
2
3
4
5
6
7
8
9
10
# OpenCV 4
find_package(OpenCV 4 REQUIRED)
add_library (robot_detector_lib SHARED RobotDetector.cpp)
target_include_directories(robot_detector_lib
PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include/robot_detector
PUBLIC ${OpenCV_INCLUDE_DIR}
)
target_link_libraries(robot_detector_lib
${OpenCV_LIBS}
)

功能包根目录的CMakeList.txt

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
add_executable(tag_detector_node 
src/tag_detector_node.cpp
)
target_link_libraries(tag_detector_node
myTagLib
${catkin_LIBRARIES}
)

add_executable(robot_detector_node
src/robot_detector_node.cpp
)
target_link_libraries(robot_detector_node
robot_detector_lib
${catkin_LIBRARIES}
)

这样就实现了两个节点分别使用不同版本的OpenCV