Intro

References

Create a ROS2 C++ Package

Create a Minimal ROS Node

  • Create a my_cpp_node node by creating a src/my_cpp_node.cpp file in the package
#include "rclcpp/rclcpp.hpp"
 
int main(int argc, char **argv)
{
    // Initiate ROS2 communications
    rclcpp::init(argc, argv);
 
    // Create a shared pointer to a a new ROS node
    // 'auto' lets the compiler infer the type (std::shared_ptr<rclcpp::Node>)
    auto node = std::make_shared<rclcpp::Node>("my_node_name");
 
    // Keep the node alive to process callbacks (subscribers, timers, services, etc.)
    rclcpp::spin(node);
 
    // Shutdown ROS2 communication and clean up resources
    rclcpp::shutdown();
 
    return 0;
}
  • Note: Everything in ROS2 C++ is managed via Smart Pointers for safety and automatic memory management, so you don’t need to worry about deallocating the node’s resources

Edit CMakeLists.txt

  • In CMakeLists.txt, add these lines after find_package(ament_cmake REQUIRED):
find_package(rclcpp REQUIRED)
find_package(std_msgs REQUIRED)
 
 
add_executable(my_cpp_node src/my_cpp_node.cpp)
ament_target_dependencies(my_cpp_node rclcpp std_msgs)
 
install(TARGETS
  my_cpp_node
  DESTINATION lib/${PROJECT_NAME}
)

Build your workspace

From the root of your workspace (ros2_ws):

# Make sure you are in the root of your workspace
cd ~/ros2_ws
 
# Build with colcon
colcon build --packages-select my_package
 
# Source the install space
source install/setup.bash

⚠️ Important: Always source install/setup.bash after building so ROS2 knows about your package.


Compile and run the node

  • Compile the node
$ colcon build --packages-select my_package
ros2 run my_package my_cpp_node
  • my_package is the package name.
  • my_cpp_node is the name of the executable you defined in CMakeLists.txt.

You should now see your ROS2 node running, and if it has logging, you’ll see the output in the terminal. hat?