How to create a simple CPP node
-
docker-compose exec dev bash
-
cd src
-
ros2 pkg create my_cpp_pkg --build-type ament_cmake --dependencies rclcpp
-
Create a CPP file:
touch my_cpp_pkg/src/my_first_node.cpp
-
Edit the file and add:
#include "rclcpp/rclcpp.hpp" int main(int argc, char **argv) { rclcpp::init(argc, argv); auto node = std::make_shared<rclcpp::Node>("cpp_test"); RCLCPP_INFO(node->get_logger(), "Hello Cpp Node"); rclcpp::spin(node); rclcpp::shutdown(); return 0; }
-
Add to
CMakeLists.txt
:// find_package... add_executable(cpp_node src/my_first_node.cpp) ament_target_dependencies(cpp_node rclcpp) install(TARGETS cpp_node DESTINATION lib/${PROJECT_NAME} ) // ament_package...
-
Run the node with:
/ros2_ws/install/my_cpp_pkg/lib/my_cpp_pkg/cpp_node
-
Source:
source ~/.bashrc
-
Run with ROS2 command:
ros2 run my_cpp_pkg cpp_node