您的代码中存在一些语法错误和潜在的问题,这可能导致编译失败。下面我将指出这些问题并提供修改后的代码:
< 和 > 应该被用来包围包含的头文件,但您的代码中使用了 < 和 >,这是HTML实体编码,而不是C++中的正确符号。
在main函数中,您使用了std::make_shared<get_imu>,这同样应该使用<和>。
在imu_callback函数中,您试图打印msg->header.stamp.nanosec,这是一个int64_t类型的值,但您使用了%d格式化字符串,这通常用于int。对于int64_t,您应该使用%ld(或对于int64_t在某些编译器中更准确的格式是%PRId64,但这需要包含<inttypes.h>)。
您的代码中有两个#include <iostream>,这是不必要的,可以删除一个。
#include <unistd.h>在这个上下文中看起来是不必要的,除非您计划在未来的代码中使用它(比如usleep)。如果不需要,可以删除它。
下面是修改后的代码:
#include "rclcpp/rclcpp.hpp"
#include <string>
#include <iostream>
#include "sensor_msgs/msg/imu.hpp"
// 删除了 std_msgs/msg/int32.hpp,因为您的代码中没有使用它
#include <chrono>
// 删除了 #include <unistd.h>,除非您确定需要它
class get_imu : public rclcpp::Node
{
public:
get_imu(std::string name) : Node(name)
{
RCLCPP_INFO(this->get_logger(), "hello,im node %s, trying to get imu data.", this->get_name().c_str());
imu_subscribe_ = this->create_subscription<sensor_msgs::msg::Imu>(
"imu", rclcpp::SensorDataQoS(),
std::bind(&get_imu::imu_callback, this, std::placeholders::_1));
}
private:
rclcpp::Subscription<sensor_msgs::msg::Imu>::SharedPtr imu_subscribe_;
void imu_callback(const sensor_msgs::msg::Imu::SharedPtr msg)
{
// 使用 %ld 或 %PRId64 来格式化 int64_t
RCLCPP_INFO(this->get_logger(), "hello,im node %s, get imu data %ld.", this->get_name().c_str(), msg->header.stamp.nanosec);
}
};
int main(int argc, char *argv[])
{
rclcpp::init(argc, argv);
// 使用 < 和 > 而不是 < 和 >
auto node = std::make_shared<get_imu>("get_imu");
rclcpp::spin(node);
rclcpp::shutdown();
return 0;
}
请尝试编译并运行修改后的代码。如果您遇到任何其他问题,请确保您已正确设置了ROS 2工作空间和编译工具链。
以上为生成回答,仅供参考~