ROS2 C++功能节点

使用功能包组织创建C++节点。

创建C++功能包

$ ros2 pkg create demo_cpp_pkg --build-type ament_cmake --license Apache-2.0
  1. ros2 pkg: 为ROS2的包管理工具,负责:创建、列出、查找功能包。
  2. create: 子命令,创建新功能包
  3. create: 子命令,创建新功能包
  4. demo_cpp_pkg:功能包名称,自己定义。
  5. --build-type ament_cmake:其中--build-type:指定编译类型,ament_cmake:表示ROS2 C++功能专用功能包。
  6. --license Apache-2.0:指定开源协议,Apache-2.0 是 ROS2 官方推荐的默认协议

运行代码结果

image image

C++ 节点代码编写

  1. 在刚创建src目录下创建cpp_node.cpp
#include "rclcpp/rclcpp.hpp"

int main(int argc, char **argv)
{
    rclcpp::init(argc, argv);
    auto node = std::make_shared<rclcpp::Node>("cpp_node");
    RCLCPP_INFO(node->get_logger(), "你好 C++ 节点!");
    rclcpp::spin(node);
    rclcpp::shutdown();
    return 0;
}
  1. 由于cpp文件不能直接运行,因此我们需要对代码进行编译。
  2. 在这里我们使用CMakeLists.txt文件进行编译测试。
  3. 在CMakeLists.txt文件中对节点进行注册和添加依赖(类似于库函数)。
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.
# find_package(<dependency> REQUIRED)
# 1. 查找 rclcpp 头文件和库
find_package(rclcpp REQUIRED)
# 2. 添加可执行文件 cpp_node
add_executable(cpp_node src/cpp_node.cpp)
# 3. 为 cpp_node 添加依赖
ament_target_dependencies(cpp_node rclcpp)
# 4. 将 cpp_node 复制到 install 目录
install(TARGETS
  cpp_node
  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()

  1. 在packages.xml中添加依赖申明。
<depend>rclcpp</depend>

6.在终端中用colcon build命令构建功能包。

colcon build
image
image
posted @ 2026-03-21 17:54  heyuikn  阅读(1)  评论(0)    收藏  举报