Intro
References
Create a ROS2 C++ Package
- If you don’t have a ROS2 C++ package, follow Create a ROS package (C++)
Create a Minimal ROS Node
- Create a
my_cpp_nodenode by creating asrc/my_cpp_node.cppfile in the package
rclcpp.cpp
#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 afterfind_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.bashafter building so ROS2 knows about your package.
Compile and run the node
- Compile the node
$ colcon build --packages-select my_packageros2 run my_package my_cpp_nodemy_packageis the package name.my_cpp_nodeis the name of the executable you defined inCMakeLists.txt.
You should now see your ROS2 node running, and if it has logging, you’ll see the output in the terminal. hat?



