Listen to this Post
ROS 2 (Robot Operating System 2) is a powerful framework for building robotic systems, leveraging the efficiency of C++ and the reliability of DDS (Data Distribution Service). This combination is ideal for both robotic applications and complex embedded systems. Below, we explore how to implement a minimal ROS 2 node using C++.
You Should Know:
1. Install ROS 2:
Ensure ROS 2 is installed on your system. For Ubuntu, use the following commands:
sudo apt update sudo apt install ros-humble-desktop source /opt/ros/humble/setup.bash
2. Create a ROS 2 Workspace:
Set up a workspace for your ROS 2 projects:
mkdir -p ~/ros2_ws/src cd ~/ros2_ws/src
- Create a Minimal ROS 2 Node in C++:
Use the following code to create a minimal ROS 2 node:#include "rclcpp/rclcpp.hpp"</li> </ol> class MinimalNode : public rclcpp::Node { public: MinimalNode() : Node("minimal_node") { RCLCPP_INFO(this->get_logger(), "Minimal ROS 2 Node has started!"); } }; int main(int argc, char * argv[]) { rclcpp::init(argc, argv); rclcpp::spin(std::make_shared<MinimalNode>()); rclcpp::shutdown(); return 0; }4. Build the Node:
Add the following lines to your `CMakeLists.txt`:
[cmake]
cmake_minimum_required(VERSION 3.5)
project(minimal_node)find_package(ament_cmake REQUIRED)
find_package(rclcpp REQUIRED)add_executable(minimal_node src/minimal_node.cpp)
ament_target_dependencies(minimal_node rclcpp)install(TARGETS minimal_node DESTINATION lib/${PROJECT_NAME})
ament_package()
[/cmake]Build the workspace:
cd ~/ros2_ws colcon build source install/setup.bash
5. Run the Node:
Execute the minimal node:
ros2 run minimal_node minimal_node
6. Verify the Output:
You should see the message:
Minimal ROS 2 Node has started!.What Undercode Say:
Combining C++ with ROS 2 provides a robust foundation for developing modern robotic and embedded systems. The integration of DDS ensures efficient communication, making it suitable for real-time applications. Practice the commands and code provided to master ROS 2 node creation. For further learning, explore the official ROS 2 documentation: ROS 2 Documentation.
References:
Reported By: Chiheb Ameur – Hackers Feeds
Extra Hub: Undercode MoN
Basic Verification: Pass ✅


