【ROS2】创建纯头文件的 C++ 功能包

首先命令行工具创建功能包。

ros2 pkg create pkg_name --build-type ament_cmake

创建 your_header.hpp,可以有多个头文件

sss2_core/
├── include/
│   └── pkg_name/
│       └── your_header.hpp
├── package.xml
├── CMakeLists.txt

修改 package.xml 至最简,可以只保留 buildtool_depend 与 export。当然,如果依赖 ros 核心通信或者其他功能包,需要对应添加和修改创建命令。

<?xml version="1.0"?>
<?xml-model href="http://download.ros.org/schema/package_format3.xsd" schematypens="http://www.w3.org/2001/XMLSchema"?>
<package format="3">
  <name>pkg_name</name>
  <version>0.0.0</version>
  <description>TODO: Package description</description>
  <maintainer email="xxx@qq.com">lxk</maintainer>
  <license>TODO: License declaration</license>

  <buildtool_depend>ament_cmake</buildtool_depend>

  <export>
    <build_type>ament_cmake</build_type>
  </export>
</package>

修改 CMakeLists.txt。不需要 add 对象,只需要 install 头文件。

cmake_minimum_required(VERSION 3.8)
project(pkg_name)

if(CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID MATCHES "Clang")
  add_compile_options(-Wall -Wextra -Wpedantic)
endif()

# find dependencies
find_package(ament_cmake REQUIRED)

install(DIRECTORY include/
  DESTINATION include
)

ament_package()

删除 src 目录。

编译后检查,install 中正确拷贝了头文件。而其他功能包使用头文件只需要添加搜索路径,而不需要链接。

find_package(pkg_name REQUIRED)
include_directories(
  ${pkg_name_INCLUDE_DIRS}
)

然后代码中。

#include <pkg_name/your_header.hpp>
上一篇
下一篇