使用__cplusplus实现C/C++互调

来源:互联网 发布:网络执法官安卓手机版 编辑:程序博客网 时间:2024/04/27 20:49

Part A
问题:
    C/C++函数如何实现互调
 
分析:
    之所以C/C++函数不能直接互调是因为在C++中函数可以重载,参数检查等特性
    如:int a(int)
    在编译后的C代码里函数名可能是_a
    在编译后的C++代码里函数名可能是a@@YAHH@Z
     (具体随编译器而定)
 
解决办法:
    在所需func()前面加上extern "C"
 
原理:
    通过extern "C"C/C++中需要调用的函数均按照C的格式进行编译
Part B 不使用__cplusplus
下面这个程序说明了C/C++之间的互调
/* main.cpp */
#include <iostream>
using namespace std;
 
extern "C" void funcC(void); // C++调用C
 
int main(void) {
    funcC();
}
 
/* cpp.cpp */
#include <iostream>
using namespace std;
 
extern "C" void funcCPP(void); // funcC调用
 
void funcCPP(void) {
    cout << "Hello, C++!" << endl;
}
 
/* c.c */
#include <stdio.h>
 
extern void funcCPP(void); // C调用C++
 
void funcC(void) {
    printf("Hello, C!/n");
    funcCPP(); // 调用funcCPP
}
可以发现这种风格很容易出错
Part C 使用__cplusplus
下面这个程序将要对外使用的函数放在头文件中,并对C/C++的兼容性进行声明
/* main.cpp */
#include <iostream>
#include "c.h"
using namespace std;
 
int main(void) {
    funcC();
}
 
/* cpp.h */
#ifndef  __CPP_H_
#define __CPP_H_
 
#ifdef __cplusplus
extern "C" {
#endif
    void funcCPP(void);
#ifdef __cplusplus
}
#endif
#endif // __CPP_H_
 
/* cpp.cpp */
#include <iostream>
#include "cpp.h"
using namespace std;
 
void funcCPP(void) {
    cout << "Hello, C++!" << endl;
}
 
/* c.h */
#ifndef  __C_H_
#define __C_H_
 
#ifdef __cplusplus
extern "C" {
#endif
    void funcC(void);
#ifdef __cplusplus
}
#endif
#endif // __C_H_
 
/* c.c */
#include <stdio.h>
#include "c.h"
#include "cpp.h"
 
void funcC(void) {
    printf("Hello, C!/n");
    funcCPP();
}
原创粉丝点击