CodeTheRobot

ROS 2 Lyrical lab 03 ยท 60 min

Build an ament C++ package

Create a package with declared dependencies and an installable rclcpp executable.

Practice this lab in your browser: First node class

Understand before building

How this part of ROS 2 works

A ROS 2 package is the smallest buildable, shareable unit. package.xml declares metadata and dependencies; CMakeLists.txt explains how C++ targets are built and installed.

A node joins the ROS graph after rclcpp is initialized. spin keeps processing callbacks until shutdown is requested.

Before you start

  • A working ~/robot_ws
  • C++ Beginner lesson 1

Files you will touch

  • src/robot_basics/package.xml
  • src/robot_basics/CMakeLists.txt
  • src/robot_basics/src/status_node.cpp

Step 1

Set up

cd ~/robot_ws/src
ros2 pkg create --build-type ament_cmake --license Apache-2.0 robot_basics --dependencies rclcpp std_msgs

Step 2

Create the file

#include <memory>
#include "rclcpp/rclcpp.hpp"

class StatusNode final : public rclcpp::Node {
public:
  StatusNode() : Node("status_node") {
    RCLCPP_INFO(get_logger(), "robot basics ready");
  }
};

int main(int argc, char ** argv) {
  rclcpp::init(argc, argv);
  rclcpp::spin(std::make_shared<StatusNode>());
  rclcpp::shutdown();
  return 0;
}

What each part does

  1. 1.The class derives from rclcpp::Node and assigns the graph name status_node.
  2. 2.rclcpp::spin processes callbacks; shutdown releases ROS resources after spin ends.

Step 3

Build, run and inspect

# Add these exact CMakeLists.txt rules after find_package(rclcpp REQUIRED):
# add_executable(status_node src/status_node.cpp)
# ament_target_dependencies(status_node rclcpp std_msgs)
# install(TARGETS status_node DESTINATION lib/${PROJECT_NAME})
cd ~/robot_ws
colcon build --packages-select robot_basics --symlink-install --event-handlers console_direct+
source install/setup.bash
ros2 run robot_basics status_node

Proof that it works

  • The package builds without warnings
  • ros2 run locates status_node
  • The log prints robot basics ready

Recovery notes

  • If the executable is not found, verify install(TARGETS status_node DESTINATION lib/${PROJECT_NAME}).
  • If a header is missing, add both find_package and ament_target_dependencies entries.
Creating a ROS 2 package