ROS实践12 自定义源文件并调用

文章目录

    • 运行环境:
    • 思路:
    • 原理:
    • 1.1 头文件编写
    • 1.2 编写源文件
    • 1.3 编写可执行文件
    • 1.4 配置文件
    • 1.5 编译运行

运行环境:

ubuntu20.04 noetic
宏基暗影骑士笔记本

思路:

上一期:类和函数:
头文件 声明
可执行文件 定义

本期:类和函数:
头文件 声明
源文件 定义
可执行文件 调用

添加include路径
新建c++库
链接c++库和ros库
链接可执行文件和新建c++库

原理:

头文件将源文件和可执行文件链接起来

1.1 头文件编写

1)在功能包下的 include/功能包名 目录下新建头文件 hello.h
2)配置 includepath 详情见上期

#ifndef _HAHA_H
#define _HAHA_H

namespace hello_ns {

class My {

public:
    void run();

};

}

#endif

1.2 编写源文件

1)在 src 目录下新建文件:haha.cpp

#include "demo01_pub/haha.h"
#include "ros/ros.h"

namespace hello_ns{

void My::run(){
    ROS_INFO("hello,head and src ...");
}

}

1.3 编写可执行文件

1)在 src 目录下新建文件 use_head.cpp
#include " 功能包/.h "

#include "ros/ros.h"
#include "demo01_pub/haha.h"

int main(int argc, char *argv[])
{
    ros::init(argc,argv,"hahah");
    hello_ns::My my;
    my.run();
    return 0;
}

1.4 配置文件

配置CMakeLists.txt文件

添加include路径
新建c++库
链接c++库和ros库

# 添加inlude路径
include_directories(
include
  ${catkin_INCLUDE_DIRS}
)

# 新建名为head的c++,将头文件和源文件添加到库中
add_library(head
  include/demo01_pub/haha.h
  src/haha.cpp
)

# 链接c++库和ros库
target_link_libraries(head
  ${catkin_LIBRARIES}
)

可执行文件配置:链接可执行文件和新建c++库

add_executable(use_head.cpp src/use_head.cpp)

target_link_libraries(use_head.cpp
  head
  ${catkin_LIBRARIES}
)

1.5 编译运行

# 编译
ctrl+shift+B

# 运行
roscore
source ./devel/setup.bash
rosrun demo01_pub use_head.cpp

在这里插入图片描述


⭐⭐⭐ 嘟嘟崽 ⭐⭐⭐
⭐⭐⭐ 祝你成功 ⭐⭐⭐

你可能感兴趣的:(ROS机器人实践,c++,开发语言)