【ROS进阶篇】第二讲 自定义头、源文件封装
文章目录
前言
在入门篇的课程中我们对于代码的封装并没有做多研究,更多的是编写cpp文件后就编译使用,而想要实现工程化的进行ROS系统使用,就需要使用头文件与源文件的方式封装代码,而对于不同的封装方式来说,编译规则的处理也不尽相同,需进一步分析。
自定义头文件封装
1. 流程
- 概念:自行设计头文件和可执行文件,并将可执行文件本身作为源文件
- 流程:
- 编写头文件
- 编写可执行文件/作为源文件
- 修改编译规则配置文件编译
2. 头文件
- 代码演示:
#ifndef _HELLO_H
#define _HELLO_H
namespace hello_ns{
class HelloPub {
public:
void run();
};
}
#endif
- 简要分析:
- 宏定义与预处理:防止头文件的重复包含和编译
#ifndef _HELLO_H //先测试x是否被宏定义过 #define _HELLO_H //程序段1 //如果x没有被宏定义过,定义x,并编译程序段 1 ... #endif //终止if
- 命名空间:防止出现标识符之间的冲突,区分类似的函数、类、变量
namespace hello_ns{ ... }
- c_cpp_properties.json:修改includepath属性防止抛出异常;
"/home/用户/工作空间/src/功能包/include/**"
3. 可执行文件
- 代码展示:
#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;
}
4. 修改编译规则
- 添加include:
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. 流程
- 概念:分别定义源文件、头文件、可执行文件,在可执行文件中包含头文件;
- 流程:
- 编写头文件;
- 编写源文件;
- 编写可执行文件;
- 编写配置文件并执行;
2. 头文件
- 代码展示:head.h
#ifndef _HEAD_H
#define _HEAD_H
namespace hello_ns {
class My {
public:
void run();
};
}
#endif
- 文件目录:功能包下的include/功能包名下(同样需要配置includepath)
3. 源文件
- 代码展示:source.cpp
#include "test_head_src/head.h"
#include "ros/ros.h"
namespace hello_ns{
void My::run(){
ROS_INFO("hello,head and src ...");
}
}
4. 可执行文件
- 代码展示:use_head.cpp
#include "ros/ros.h"
#include "test_head_src/head.h"
int main(int argc, char *argv[])
{
ros::init(argc,argv,"hahah");
hello_ns::My my;
my.run();
return 0;
}
5. 修改编译规则
- 头文件与源文件:
- include项:
include_directories( include ${catkin_INCLUDE_DIRS} )
- 声明C++库
add_library(head include/test_head_src/head.h src/source.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_head head ${catkin_LIBRARIES} )
总结
- 声明:本节博客部分参考了CSDN用户赵虚左的ROS教程,下篇博客将会主要聚焦于ROS的运行管理上,介绍元功能包与工作空间覆盖的概念。