ros2

功能包(pkg)

一个功能包可以被认为是ROS2代码的容器。如果希望能够管理代码或与他人共享代码,那么需要将其组织在一个包中。通过包,可以发布ROS2工作,并允许其他人轻松地构建和使用它。

功能包 和 程序 的关系

一个功能包里可以包含多个程序。这些程序分成不同职责,共同构成一个功能包的完整功能。通过cmake可控制多个可执行文件:

1
2
3
4
5
# ...
add_executable(program1 src/program1.cpp ...)
# ...
add_executable(program2 src/program2.cpp ...)
# ...

创建并运行一个功能包

  1. 使用如下命令在当前目录下创建一个ros2包:
1
ros2 pkg create <包名> --build-type ament_cmake --node-name <程序名> --dependencies <依赖>
  • ros2 pkg create:创建包的 固定语法
  • --build-type:构建包的选项,一般C++写ament_cmake,python写 ament_python
  • --node-name:可选参数,若指定将会默认添加一个src/<程序名>.cpp文件,并指定成程序名称。
  • --dependencies:可选参数,添加依赖项,常见的依赖如rclcpp(ros2的c++接口)。

下图为在ubuntu命令行创建一个名为demo_cpp_pkg的包的示例:

一个包的基本结构:

1
2
3
4
5
demo_cpp_pkg/
├── CMakeLists.txt 编译配置
├── package.xml 包元信息
├── src/ 你自己写代码的地方
└── include/demo_cpp_pkg/ (可选)头文件
  1. 新建src/main.cpp,写入如下基本节点代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include "rclcpp/rclcpp.hpp"

using namespace rclcpp;
using namespace std;

int main(int argc, char** argv)
{
rclcpp::init(argc, argv);
auto node = std::make_shared<Node>("cpp_node");
RCLCPP_INFO(node->get_logger(), "你好!C++节点");
rclcpp::spin(node);
rclcpp::shutdown();
return 0;
}
  1. 修改CMakeLists.txt成如下所示:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
cmake_minimum_required(VERSION 3.8)
project(demo_cpp_pkg)

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)
# uncomment the following section in order to fill in
# further dependencies manually.
# 1. 查找rclcpp的头文件和库
find_package(rclcpp REQUIRED)
# 2. 添加可执行文件 main
add_executable(main src/main.cpp)
# 3. 为 main 添加依赖
ament_target_dependencies(
main
rclcpp
)
# 4. 将 main拷贝到 install目录
install(TARGETS
main
DESTINATION lib/${PROJECT_NAME})

if(BUILD_TESTING)
find_package(ament_lint_auto REQUIRED)
# the following line skips the linter which checks for copyrights
# comment the line when a copyright and license is added to all source files
set(ament_cmake_copyright_FOUND TRUE)
# the following line skips cpplint (only works in a git repo)
# comment the line when this package is in a git repo and when
# a copyright and license is added to all source files
set(ament_cmake_cpplint_FOUND TRUE)
ament_lint_auto_find_test_dependencies()
endif()

ament_package()

其中:ament_target_dependencies函数是ament的扩展函数,等同于绑定依赖的include库和链接libraries,即下两行代码:

1
2
target_include_directories(main PUBLIC ${rclcpp_INCLUDE_DIRS})
target_link_libraries(main ${rclcpp_LIBRARIES})
  1. 使用cmake编译(vscode按下f7)。

  2. 使用colcon构建包:colcon build

  3. source install/setup/bash

  4. 运行命令

    1
    ros2 run <包名> <程序名>

    示例中即为:

    1
    ros2 run demo_cpp_pkg main

ros2
https://becks723.github.io/2025/06/11/ros2/
作者
Becks723
发布于
2025年6月11日
许可协议