ROS: 創建並運行一個c++的demo

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

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章