在入门篇的课程中我们对于代码的封装并没有做多研究,更多的是编写cpp文件后就编译使用,而想要实现工程化的进行ROS系统使用,就需要使用头文件与源文件的方式封装代码,而对于不同的封装方式来说,编译规则的处理也不尽相同,需进一步分析。
- 编写头文件
- 编写可执行文件/作为源文件
- 修改编译规则配置文件编译
#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
- 1
- 2
- 3
- 4
- 命名空间:防止出现标识符之间的冲突,区分类似的函数、类、变量
namespace hello_ns{ ... }
- 1
- 2
- 3
"/home/用户/工作空间/src/功能包/include/**"
#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;
}
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}
)
- 编写头文件;
- 编写源文件;
- 编写可执行文件;
- 编写配置文件并执行;
#ifndef _HEAD_H
#define _HEAD_H
namespace hello_ns {
class My {
public:
void run();
};
}
#endif
#include "test_head_src/head.h"
#include "ros/ros.h"
namespace hello_ns{
void My::run(){
ROS_INFO("hello,head and src ...");
}
}
#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;
}
- include项:
include_directories( include ${catkin_INCLUDE_DIRS} )
- 1
- 2
- 3
- 4
- 声明C++库
add_library(head include/test_head_src/head.h src/source.cpp )
- 1
- 2
- 3
- 4
- 依赖项与链接
add_dependencies(head >${${PROJECT_NAME}_EXPORTED_TARGETS} >${catkin_EXPORTED_TARGETS}) target_link_libraries(head ${catkin_LIBRARIES} )
- 1
- 2
- 3
- 4
- 5
依赖项与链接:
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} )
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9