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();
}