ROS2与C++入门教程-增加头文件
ROS2与C++入门教程-增加头文件
说明 :
- 介绍如何增加头文件来声明类或函数
- 目前在ros2里一般声明和定义写在一个源文件里。 对于小项目这样处理也很方便,比如一个订阅或发布的小程序。
- 但是对于大项目,都放在一个源文件,管理起来就不太方便。一般都按照类型分到不同的源文件。那就是要把声明和定义分开。
步骤:
- 新建一个包cpp_header
cd ~/dev_ws/src
ros2 pkg create --build-type ament_cmake cpp_header
- 进入include,新建头文件minimal_publisher.hpp
cd ~/dev_ws/src/cpp_header/include/cpp_header
touch minimal_publisher.hpp
- 内容如下:
#include <chrono>
#include <functional>
#include <memory>
#include <string>
#include "rclcpp/rclcpp.hpp"
#include "std_msgs/msg/string.hpp"
using namespace std::chrono_literals;
class MinimalPublisher : public rclcpp::Node
{
public:
MinimalPublisher();
private:
void timer_callback();
rclcpp::TimerBase::SharedPtr timer_;
rclcpp::Publisher<std_msgs::msg::String>::SharedPtr publisher_;
size_t count_;
};
- 进入src目录,新建文件minimal_publisher.cpp
cd ~/dev_ws/src/cpp_header/src
touch minimal_publisher.cpp
- 内容如下:
#include "cpp_header/minimal_publisher.hpp"
MinimalPublisher::MinimalPublisher ()
: Node("minimal_publisher"), count_(0)
{
publisher_ = this->create_publisher<std_msgs::msg::String>("topic", 10);
timer_ = this->create_wall_timer(
500ms, std::bind(&MinimalPublisher::timer_callback, this));
}
void MinimalPublisher::timer_callback()
{
auto message = std_msgs::msg::String();
message.data = "Hello, world! " + std::to_string(count_++);
RCLCPP_INFO(this->get_logger(), "Publishing: '%s'", message.data.c_str());
publisher_->publish(message);
}
- 进入src目录,新建文件minimal_publisher_node.cpp
cd ~/dev_ws/src/cpp_header/src
touch minimal_publisher_node.cpp
- 内容如下:
#include "cpp_header/minimal_publisher.hpp"
int main(int argc, char * argv[])
{
rclcpp::init(argc, argv);
rclcpp::spin(std::make_shared<MinimalPublisher>());
rclcpp::shutdown();
return 0;
}
- 编辑package.xml
- 在<buildtool_depend>ament_cmake</buildtool_depend>后增加
<depend>rclcpp</depend>
<depend>std_msgs</depend>
- 编辑 CMakelist.txt
- 在find_package(ament_cmake REQUIRED)后增加
find_package(rclcpp REQUIRED)
find_package(std_msgs REQUIRED)
- 再增加可执行文件,ros2 run能够调用的名称
include_directories(include)
add_executable(talker src/minimal_publisher_node.cpp src/minimal_publisher.cpp)
ament_target_dependencies(talker rclcpp std_msgs)
- 增加可执行文件位置,ros2 run可以找到这个可执行文件
install(TARGETS
talker
DESTINATION lib/${PROJECT_NAME})
- 安装相关依赖
cd ~/dev_ws/
rosdep install -i --from-path src --rosdistro galactic -y
- 编译包
colcon build --symlink-install --packages-select cpp_header
- 加载工作空间
. install/setup.bash
- 执行
ros2 run cpp_header talker
- 效果如下:
$ ros2 run cpp_header talker
[INFO] [1651805635.082660387] [minimal_publisher]: Publishing: 'Hello, world! 0'
[INFO] [1651805635.582651708] [minimal_publisher]: Publishing: 'Hello, world! 1'
[INFO] [1651805636.082660773] [minimal_publisher]: Publishing: 'Hello, world! 2'
[INFO] [1651805636.582671075] [minimal_publisher]: Publishing: 'Hello, world! 3'
[INFO] [1651805637.082674760] [minimal_publisher]: Publishing: 'Hello, world! 4'
获取最新文章: 扫一扫右上角的二维码加入“创客智造”公众号