写在前面,本系列笔记参考的是AutoLabor的教程,具体项目地址在 这里
本节主要介绍ROS的C++实现中,如何使用头文件与源文件的方式封装代码,具体内容如下:
在ROS中关于头文件的使用,核心内容在于CMakeLists.txt文件的配置,不同的封装方式,配置上也有差异。
需求: 设计头文件,可执行文件本身作为源文件。
流程:
1、头文件
再功能包的include/功能包名
目录下新建头文件:hello.h
,示例内容如下:
#ifndef _HELLO_H
#define _HELLO_Hnamespace hello_ns{class HelloPub {public:void run();
};}#endif
注意:
在VsCode中,为了后续包含头文件时不抛出异常,请配置.vscode
下的c_cpp_properties.json
的includepath
属性。
"/home/用户/工作空间/src/功能包/include/**"
2、可执行文件
在src目录下新建文件:hello.cpp
,示例内容如下:
#include "ros/ros.h"
#include "test_head/hello.h"namespace hello_ns {void HelloPub::run(){ROS_INFO("自定义头文件的使用....");
}}int main(int argc, char *argv[])
{setlocale(LC_ALL,"");ros::init(argc,argv,"test_head_node");hello_ns::HelloPub helloPub;helloPub.run();return 0;
}
3、配置CMakeLists.txt
文件
配置CMakeLists.txt文件,头文件相关配置如下:
include_directories(
include${catkin_INCLUDE_DIRS}
)
可执行配置文件配置方式和之前一致:
add_executable(hello src/hello.cpp)add_dependencies(hello ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})target_link_libraries(hello${catkin_LIBRARIES}
)
最后编译并执行,控制台可以输出自定义的文本信息。
效果如下:
**需求:**设计头文件与源文件,在可执行文件中包含头文件。
流程:
1、头文件
头文件的设置和3.2.1类似,在功能包下的include/功能包名
目录下,新建头文件haha.h
,示例内容如下:
#ifndef _HAHA_H
#define _HAHA_Hnamespace hello_ns {class My {public:void run();};}#endif
2、源文件
在src目录下新建文件:haha.cpp
,示例内容如下:
#include "test_head_src/haha.h"
#include "ros/ros.h"namespace hello_ns{void My::run(){ROS_INFO("hello,head and src ...");
}}
3、可执行文件
在src目录下新建文件:use_head.cpp
,示例内容如下:
#include "ros/ros.h"
#include "test_head_src/haha.h"int main(int argc, char *argv[])
{ros::init(argc,argv,"hahah");hello_ns::My my;my.run();return 0;
}
4、配置CMakeLists.txt
文件
头文件与源文件相关配置:
include_directories(
include${catkin_INCLUDE_DIRS}
)## 声明C++库
add_library(headinclude/test_head_src/haha.hsrc/haha.cpp
)add_dependencies(head ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})target_link_libraries(head${catkin_LIBRARIES}
)
可执行文件配置:
add_executable(use_head src/use_head.cpp)add_dependencies(use_head ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})#此处需要添加之前设置的 head 库
target_link_libraries(use_headhead${catkin_LIBRARIES}
)
结果示例:
与C++类似的,在Python中导入其他模块时,也需要相关处理。
**需求:**首先新建一个Python文件A,再创建Python文件UseA,在UseA中导入A并调用A的实现。
实现:
1、新建两个Python文件并使用import导入
文件A实现(包含一个变量)
#! /usr/bin/env python
num = 1000
文件B核心实现
import os
import syspath = os.path.abspath(".")
# 核心
sys.path.insert(0,path + "/src/plumbing_pub_sub/scripts")import tools....
....rospy.loginfo("num = %d",tools.num)
2、添加可执行权限,编辑配置文件并执行
略
示例结果:
http://www.autolabor.com.cn/book/ROSTutorials/di-2-zhang-ros-jia-gou-she-ji/23-fu-wu-tong-xin/224-fu-wu-tong-xin-zi-ding-yi-srv-diao-yong-b-python.html