5.编写源代码

在上述(4)CMakelists.txt文件的可执行文件创建部分(add_executable)中,进行了以下设置。
add_executable(hello_world_node src/hello_world_node.cpp) 

换句话说,是引用功能包的src目录中的hello_world_node.cpp源代码来生成hello_world_node可执行文件。由于这里没有hello_world_node.cpp源代码,我们来写一个简单的例子。

首先,用cd命令转到功能包目录中包含源代码的目录(src),并创建hello_world_node.cpp文件。这个例子使用gedit编辑器,但是您可以使用自己的编辑器,比如vi、gedit、qtcreator、vim或者emacs。
$ cd ~/catkin_ws/src/my_first_ros_pkg/src/
$ gedit hello_world_node.cpp

之后如下修改代码。

#include <ros/ros.h>
#include <std_msgs/String.h>
#include <sstream>
int main(int argc, char **argv)
{
 ros::init(argc, argv, "hello_world_node");
 ros::NodeHandle nh;
 ros::Publisher chatter_pub = nh.advertise<std_msgs::String>("say_hello_world", 1000);
 ros::Rate loop_rate(10);
 int count = 0;

  while (ros::ok())
 {
 std_msgs::String msg;
 std::stringstream ss;
 ss << "hello world!" << count;
 msg.data = ss.str();
 ROS_INFO("%s", msg.data.c_str());
 chatter_pub.publish(msg);
 ros::spinOnce();
 loop_rate.sleep();
 ++count;
 }
 return 0;
}

猜你喜欢

转载自blog.csdn.net/wccsu1994/article/details/84532258