最终调用如下。
/**
* call.c
*/
#include "called.h"
int
main(int argc, char const* argv[]) {
PrintCpp();
return 0;
}
(二) 调用类成员函数(接口函数没有类指针)
被调用函数声明和定义如下。
/**
* called.h
*/
#ifndef CALLED_H
#define CALLED_H
class Console {
public:
Console();
virtual void PrintDouble(double num);
};
extern "C" void CppPrintDouble(double num);
#endif
/**
* called.cpp
*/
#include <iostream>
#include "called.h"
using namespace std;
Console::Console() {}
void
Console::PrintDouble(double num) {
cout << num << endl;
}
Console* console = new Console();
void
CppPrintDouble(double num) {
console->PrintDouble(num);
}
最终调用如下。
/**
* call.c
*/
#include "called.h"
int
main(int argc, char const* argv[]) {
CppPrintDouble(3.14);
return 0;
}
五、C++ 函数调用 C 接口
被调用函数的声明和定义如下。
/** * called.h */ #ifndef CALLED_H #define CALLED_H void PrintC(void); #endif
/**
* called.c
*/
#include <stdio.h>
#ifdef __cplusplus
extern "C" {
#endif
#include "called.h"
#ifdef __cplusplus
};
#endif
void
PrintC(void) {
printf("I'm C.n");
}
最终调用如下。
/**
* call.cpp
*/
#ifdef __cplusplus
extern "C" {
#endif
#include "called.h"
#ifdef __cplusplus
};
#endif
int
main(int argc, char const* argv[]) {
PrintC();
return 0;
}
在 called.c 文件中,#ifdef __cplusplus /*...*/ #endif 和 extern "C" 的作用是防止 g++ 编译器对“.c”文件用 C++ 的方式编译,如果用 gcc 进行编译,则直接写 #include "called.h" 就行。
到此这篇关于C 与 C++ 接口函数相互调用的实现的文章就介绍到这了,更多相关C 与 C++ 接口函数调用内容请搜索易采站长站以前的文章或继续浏览下面的相关文章希望大家以后多多支持易采站长站!










