Skip to content

在C++中调用C函数

  • C/C++

今天在做项目的时候遇到了C++里面要调用C语言写的库,要用里面的函数,调用的时候会报错,google了一下发现原来需要声明一下,现在总结一下。
在调用之前要使用 extern “C”关键字声明在编译的时候要用C的编译器编译声明包含的部分,这里要包含所有用到的C头文件和C函数,并且在函数前也需要使用“extern”关键字,像下面这样:

extern "C"
{
#include 
extern int unqlite_open(unqlite **ppDB,const char *zFilename,unsigned int iMode);
extern int unqlite_kv_store(unqlite *pDb,const void *pKey,int nKeyLen,const void *pData,unqlite_int64 nDataLen);
extern int unqlite_kv_fetch(unqlite *pDb,const void *pKey,int nKeyLen,void *pBuf,unqlite_int64 /* in|out */*pBufLen);
extern int unqlite_close(unqlite *pDb);
}

这时候再编译就没有问题了,必须这么做是因为C的编译器和C++的编译器在编译之后产生的函数名不同,因为C++有重载的,所以编译后的函数名会在方法后面加上参数和返回值类型,例如void func(int),最终会被编译成func_int类似这样的函数,而C语言的编译器不会这么处理,最后就导致你调用的C语言的函数void func(int)变成了func_int,在类库里当然找不到了。

0 0 votes
Article Rating
Tags:
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x