1. 创建catkin工作空间
$ mkdir -p ~/catkin_ws/src
$ cd ~/catkin_ws/src
2. 编译catkin工作空间
$ cd ~/catkin_ws/
$ catkin_make
3.配置环境变量
$ source devel/setup.bash
把上述指令添加至.bashrc文件中,如下:
通过命令:vim ~/.bashrc , 在.bashrc文件中添加相应的命令
4. 创建工作包
cd catkin_ws/src
catkin_create_pkg hello std_msgs roscpp rospy
我们可以看见功能包内包含以下文件:
CMakeLists.txt package.xml
创建src文件
mkdir src
cd src
创建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!");
}
修改CMakeLists.txt
cmake_minimum_required(VERSION 2.8.3)
project(agitr)
#添加需要的依赖库 roscpp
find_package(catkin REQUIRED COMPONENTS roscpp)
include_directories(
${catkin_INCLUDE_DIRS}
)
#声明想要的可执行文件的文件名,以及所需要的源列表,如果有多个源列表,空格列在此处
add_executable(hello src/hello.cpp)
#告诉Cmake当链接此可执行文件时需要链接哪些库
target_link_libraries(hello ${catkin_LIBRARIES})
这里一定要注意: add_executable(hello src/hello.cpp) 中是src/hello.cpp, 否则编译时会出现如下:
-- Configuring done
CMake Error at hello/CMakeLists.txt:209 (add_executable):
Cannot find source file:
hello.cpp
Tried extensions .c .C .c++ .cc .cpp .cxx .m .M .mm .h .hh .h++ .hm .hpp
.hxx .in .txx
CMake Error: CMake can not determine linker language for target: hello
CMake Error: Cannot determine link language for target "hello".
修改package.xml
添加如下代码:
<build_depend>roscpp</build_depend>
<exec_depend>roscpp</exec_depend>
退回到catkin_ws工作区并编译
cd ~/catkin_ws
catkin_make
运行hello.cpp
新建一个终端: roscore
再建一个终端: rosrun hello hello
运行结果:
[ INFO] [1573281067.719736559]: hello, ros!
参考:https://blog.csdn.net/QFJIZHI/article/details/82978447