ROS c++内嵌c语言(一):c头文件处理

6 篇文章 1 订阅

背景

ROS开发过程中涉及到.cpp文件调用.c文件的函数,编译时报警.c中被调用的函数未定义:
main_window.cpp:(.text+0x36dc):对‘jt_to_CartesianPose(float*,float*)’未定义的引用

CMakeFiles/qtros.dir/src/main_window.cpp.o:在函数‘qtros::MainWindow::update_listView_CartesianPose(sensor_msgs::JointState_<std::allocator<void> > const&)’中:
main_window.cpp:(.text+0x36dc):对‘jt_to_CartesianPose(float*,float*)’未定义的引用
collect2: error: ld returned 1 exit status
qtros/CMakeFiles/qtros.dir/build.make:557: recipe for target '/home/ros_gui_ws/catkin_ws/devel/lib/qtros/qtros' failed
make[2]: *** [/home/ros_gui_ws/catkin_ws/devel/lib/qtros/qtros] Error 1
CMakeFiles/Makefile2:1360: recipe for target 'qtros/CMakeFiles/qtros.dir/all' failed
make[1]: *** [qtros/CMakeFiles/qtros.dir/all] Error 2
Makefile:140: recipe for target 'all' failed
make: *** [all] Error 2
Invoking "make -j3 -l3" failed

原因分析

在调用jt_to_CartesianPose前,cpp文件对c语言头文件的包含后,编译正常,说明c文件的包含关系是正确的。当调用具体函数时,编译报警,分析是对jt_to_CartesianPose的外部声明出现问题,导致cpp文件无法找到jt_to_CartesianPose的路径。

查看 joint_to_CartesianPose 的 .h文件,发现extern void joint_to_CartesianPose(float *joint_value,float *new_jt);被放到了extern "C"区域外侧导致c++编译器在编译C语言函数时找不到链接路径而报错

#ifndef     _RC_MODEL_H_
#define     _RC_MODEL_H_

#ifdef __cplusplus
extern "C"{
#endif


#ifdef __cplusplus
}
#endif

extern void joint_to_CartesianPose(float *joint_value,float *new_jt); // (放到了extern "C"区域外)

#endif

解决方案

#ifndef     _RC_MODEL_H_
#define     _RC_MODEL_H_

#ifdef __cplusplus
extern "C"{
#endif

extern void joint_to_CartesianPose(float *joint_value,float *new_jt); // (调整到extern "C"区域内)

#ifdef __cplusplus
}
#endif

#endif

再次编译,成功!

补充(重要)

__cplusplus宏简单介绍:

在C语言gcc编译器中是没有__cplusplus这个宏,而g++预编译之后,能够识别__cplusplus这个宏。

在使用c++编译器编译其他语言(这里是C语言,得编译器支持的语言)时,用上这样的方式,可以让编译器把extern “C”代码块中的内容按照C语言的编译方式进行编译。因为c++中支持函数重载,而C语言不支持,c++对函数经过了其他处理,如果不加extern “C”限制按照C语言的方式编译,那么c++编译器在编译C语言函数时可能就会找不到链接路径而报错

参考链接:https://www.cnblogs.com/yangguang-it/p/6720211.html

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值