专栏中心

EEPW首页 > 专栏 > c++调用c函数

c++调用c函数

发布人:电子禅石 时间:2020-02-19 来源:工程师 发布文章

直接遇到的问题是:直接在c++ 的程序中调用.so 的动态库中函数,发现总是:

找不到函数。

最后:发现在声明的时候,加上extern "C" 就可以了。原因可能是 不加的话,声明部分c++ 也会按普通方式处理。

extern "C"{
int write_keypair_with_keyID(unsigned int keyID,unsigned int keyType,unsigned char *keyprivate,unsigned int key_private_len,unsigned char *keypubkey,unsigned int key_pubkey_len);
}

出现这个的问题是:在包含这个函数的头文件中,前面的define 给定义成了其他的。比如SAN_CHIP,然后在.C 文件中 include 也是SAN_CHIP,然后后面的就其实不include 了。所以说没有这个函数的声明。

#ifndef _SAN_CHIP_H__
#define _SAN_CHIP_H__


math.c使用c语言写的main.cpp是c++写的。

gcc -c math.c生成math.o

ar -r librmath.a *.o//把math.o打包成静态库rmath.a

g++ main.cpp -L./  -lrmath

-L静态库路径 

-l静态库名字

在math.h中加入extern "C"就行了

---------------------------------------------------------------------------------------------------------

math.c

1 #include "math.h"
 2 int func(int a,int b)
 3 {
 4     return a+b;
 5 }

------------------------------------------------------------------------------------------------------------

math.h

1 #ifndef __MATH_H__
 2 #define __MATH_H__
 3
 4 #ifdef __cplusplus
 5 extern "C"
 6 {
 7 #endif
 8 int func(int,int);
 9 #ifdef __cplusplus
10 }
11 #endif
12
13 #endif

----------------------------------------------------------------------------------------------------------

main.cpp

1 #include "math.h"
 2 #include <iostream>
 3 using namespace std;
 4 int main()
 5 {
 6     int a= 2,b = 3;
 7     int c = func(a,b);
 8     cout << c << endl;
 9 }


专栏文章内容及配图由作者撰写发布,仅供工程师学习之用,如有侵权或者其他违规问题,请联系本站处理。 联系我们

关键词: C++
更多 培训课堂
更多 焦点
更多 视频

技术专区