ROS引用头文件及动态链接库的方法

您所在的位置:网站首页 ros_lib ROS引用头文件及动态链接库的方法

ROS引用头文件及动态链接库的方法

#ROS引用头文件及动态链接库的方法| 来源: 网络整理| 查看: 265

文章目录 (1)引用自定义头文件(2)引用同一工作空间的头文件(3)引用动态链接库

(1)引用自定义头文件

自定义一个头文件:add_count.h,预定义 INIT_COUNT = 89 ;函数 add_num()

#ifndef _add_count_ #define _add_count_ #define INIT_COUNT 89 int add_num(int a , int b); #endif

创建package_h_learn包, 修改CMakeLists.txt: 指定头文件位置,在include文件夹,将.h文件放入include文件夹

## Specify additional locations of header files ## Your package locations should be listed before other locations include_directories( include ${catkin_INCLUDE_DIRS} ) .... .... .... add_executable(h_learn src/h_learn.cpp) target_link_libraries(h_learn ${catkin_LIBRARIES})

h_learn.cpp代码:

#include "ros/ros.h" #include "std_msgs/String.h" #include #include "package_h_learn/add_count.h" //引用自定义的头文件 int add_num(int a , int b) //头文件函数声明的实现 { int sum; sum = a + b; return sum; } int main(int argc, char **argv) { ros::init(argc,argv,"h_learn"); ros::NodeHandle n; ros::Publisher pub = n.advertise("listener",1000); ros::Rate loop_rate(10); int count =INIT_COUNT; //头文件宏定义初始化INIT_COUNT int num; num = add_num(count,5); while(ros::ok()) { std_msgs::String msg; std::stringstream ss; ss ros::init(argc,argv,"h_learn"); ros::NodeHandle n; ros::Publisher pub = n.advertise("listener",1000); ros::Rate loop_rate(10); int count =INIT_COUNT; //头文件宏定义初始化INIT_COUNT int num; num = add_num(count,15); while(ros::ok()) { std_msgs::String msg; std::stringstream ss; ss #endif int multiply(int a, int b); #ifndef __cpluscplus } #endif #endif

接下来生成动态链接库*.so文件,注意-share 和 -fPIC 参数很重要 -share:告诉gcc要生成的是动态链接库 -fPIC:告诉gcc生成的代码是非位置依赖的,方便用于动态链接

g++ multiply.cpp -fPIC -shared -o libmultiply.so

在ros工作空间创建一个包test_package,multiply.h放在include/tesk_pkg目录下,libmultiply.so放在lib目录下。

CMakeLists.txt需要做如下修改:

include_directories :需要包含头文件link_directories :用于添加第三方库路径,catkin_LIB_DIRS表示创建环境变量,${catkin_LIB_DIRS}为取该环境变量的值,lib是相对于当前软件包所在路径的相对路径target_link_libraries :引用动态链接库,这里去掉lib前缀,去掉.so,直接写multiply ## Specify additional locations of header files ## Your package locations should be listed before other locations include_directories( include ${catkin_INCLUDE_DIRS} ) link_directories( lib ${catkin_LIB_DIRS} ) ... ... ... add_executable(test_pkg src/test_pkg.cpp) #add_dependencies(h_learn test1_generate_message_cpp) target_link_libraries(test_pkg ${catkin_LIBRARIES} multiply )

src/test_pkg.cpp代码如下:

#include "ros/ros.h" #include "std_msgs/String.h" #include #include "test_package/multiply.h" int main(int argc, char **argv) { ros::init(argc,argv,"h_learn"); ros::NodeHandle n; ros::Publisher pub = n.advertise("listener",1000); ros::Rate loop_rate(10); //.so int num = multiply(5,5); while(ros::ok()) { std_msgs::String msg; std::stringstream ss; ss


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3