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();
}
函数重载编译兼容性跨语言调用],
C/C++互调实践
3281

被折叠的 条评论
为什么被折叠?



