注意这个文件目录的结构,尤其是 hello.h 这个自定义的头文件在 include/plumbing_head
文件夹之下,这个会直接影响后续头文件的引用。
hello.h文件的内容
#ifndef _HELLO_H
#define _HELLO_H
namespace hello_ns{
class HelloPub {
public:void run();
};
}
#endif
src下面定义hello.cpp
hello.cpp的内容
#include "ros/ros.h"
#include "plumbing_head/hello.h"
//"/home/Documents/learn/ros/ros_ws_demo1/src/plumbing_head/include/**",
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;
}
"includePath": ["/home/Documents/learn/ros/ros_ws_demo1/src/plumbing_head/include/**"],
include_directories(include${catkin_INCLUDE_DIRS}
)
add_executable(hello_node src/hello.cpp)
add_dependencies(hello_node ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})
target_link_libraries(hello_node${catkin_LIBRARIES}
)
同样是在该工作空间下,定义haha.cpp 和 test_haha.cpp,一个为源文件,一个为测试文件。实现逻辑为:在haha.cpp中对函数进行了定义,而test_haha.cpp中对haha.cpp中定义的函数进行调用。
haha.cpp 内容
#include "plumbing_head/hello.h"
#include "ros/ros.h"
namespace hello_ns{
void HelloPub::run(){ROS_INFO("hello,head and src ...");
}
}
test_haha.cpp内容
#include "ros/ros.h"
#include "plumbing_head/hello.h"
int main(int argc,char *argv[]){ros::init(argc,argv,"head_src");hello_ns::HelloPub helloPub;helloPub.run();return 0;
}
add_library(head_srcinclude/${PROJECT_NAME}/hello.hsrc/haha.cpp
)
add_dependencies(head_src ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})
add_executable(test_haha_node src/test_haha.cpp)
add_dependencies(test_haha_node ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})
target_link_libraries(head_src${catkin_LIBRARIES}
)
target_link_libraries(test_haha_nodehead_src${catkin_LIBRARIES}
)
Python的文件结构如下
haha.py
num = 10
test_haha.py
#! /usr/bin/env python
# -*- coding:utf-8 -*-import os
import sys
import rospy
p = os.path.abspath(".")
rospy.loginfo("*"*10+p)
# 临时环境变量,不然无法加载到 haha.py,,因为在运行过程中,默认路径为工作空间目录而不是scripts目录
sys.path.insert(0,p + "/src/plumbing_head/scripts")
import haha
if __name__=="__main__":rospy.init_node("hah")
#rospy.loginfo("*"*10+os.path.abspath("."))rospy.loginfo(haha.num)
【注】注意修改上面两个py文件的执行权限。
catkin_install_python(PROGRAMSscripts/haha.pyscripts/test_haha.pyDESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
)
然后运行即可