ROS学习记录(十一):头文件
ROS学习记录(十一):头文件
自定义头文件调用
一、方法一
可执行文件本身作为源文件。
流程:
- 编写头文件;
- 编写可执行文件(同时也是源文件);
- 编辑配置文件并执行。
1.头文件
在功能包下的 include/功能包名 目录下新建头文件: hello.h
1
2
3
4
5
6
7
8
9
10
#ifndef _HELLO_H
#define _HELLO_H
namespace hello_ns{//命名空间
class HelloPub //类名
{
public:
void run();
};
}
#endif
在 VScode 中,为了后续包含头文件时不抛出异常,请配置 .vscode 下 c_cpp_properties.json 的 includepath 属性
1
"/home/用户/工作空间/src/功能包/include/**"
2.可执行文件
在 src 目录下新建文件:hello.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#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文件,头文件相关配置如下:
1
2
3
4
include_directories(
include#原本include是被注释的
${catkin_INCLUDE_DIRS}
)
其余与前面是相同的
1
2
3
4
5
6
7
add_executable(hello src/hello.cpp)
add_dependencies(hello ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})
target_link_libraries(hello
${catkin_LIBRARIES}
)
一、方法二
1.头文件
该步骤与方法一是相同的,直接复制即可。
2.源文件
在 src 目录下新建文件:hello.cpp,这一点与之前不同,之前的源文件即函数都在可执行文件中,为了实际应用中方便复用等操作,建议使用方法二的编写步骤,尽管方法二的过程相较于方法一复杂一些
1
2
3
4
5
6
7
8
#include "test_head_src/hello.h"
#include "ros/ros.h"
namespace hello_ns{
void HelloPub::run(){
ROS_INFO("自定义头文件的使用....");
}
}
3.可执行文件
在 src 目录下新建文件:use_head.cpp,在该文件中直接调用头文件和函数即可
1
2
3
4
5
6
7
8
9
10
#include "ros/ros.h"
#include "test_head_src/hello.h"
int main(int argc, char *argv[])
{
ros::init(argc,argv,"helloh");
hello_ns::HelloPub my;
my.run();
return 0;
}
4.配置文件
头文件与源文件相关配置:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
include_directories(
include
${catkin_INCLUDE_DIRS}
)
## 声明C++库 ,将头文件和源文件链接起来
add_library(head
include/test_head_src/haha.h
src/haha.cpp
)
add_dependencies(head ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})
target_link_libraries(head
${catkin_LIBRARIES}
)
可执行文件配置:
1
2
3
4
5
6
7
8
9
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}
)
本文由作者按照 CC BY 4.0 进行授权