操作系统: Ubuntu16.04

ROS版本: Kinetic

1.安装ROS,详情见http://blog.csdn.net/qq_17232031/article/details/79519308

2.建立一个catkin_ws文件夹,以及子目录src:

$ mkdir catkin_ws
$ cd ./catkin_ws
$ mkdir src

3.在src目录下创建功能包,命名为first

$ catkin_create_pkg first

此时会产生first文件夹,其中包含两个文件,CMakelists.txt和package.xml

4.在first文件夹下,新建hello.cpp文件

$ sudo gedit hello.cpp

编写代码:

#include <ros/ros.h>

int main(int argc,char ** argv)
{
    ros::init(argc,argv,"hello_ros");
    ros::NodeHandle nh;
    ROS_INFO_STREAM("Hello ROS");
}

init函数初始化客户端库。NodeHandle节点句柄,用于程序与ROS的交互。

5.编译cpp代码,此时需要对同目录下的CMakelists.txt和package.xml文件进行修改

在CMakelist.txt文件中添加

add_executable(hello hello.cpp)
target_link_libraries(hello ${catkin_LLIBRARIES})

并且将

find_package(catkin REQUIRED)

改为:

find_package(catkin REQUIRED COMPONENTS roscpp)

这句是为了添加roscpp依赖项

修改package.xml文件,添加build_depend编译依赖和run_depend运行依赖

<build_depend>roscpp</build_depend>
<run_depend>roscpp<run_depend>

然后,在catkin_ws目录下执行:

$ catkin_make
$ cd ./devel
$ source setup.bash

6. 运行程序

$ rosrun first hello

出现结果: