C++ 如何布局混合C和C的函数原型+;
我想从.c和.cpp文件中包含一个头文件 所以我知道名字弄乱和外部“C”所以 但是当我将其包含在.c文件中时,由于C++ 如何布局混合C和C的函数原型+;,c++,c,name-mangling,extern-c,C++,C,Name Mangling,Extern C,我想从.c和.cpp文件中包含一个头文件 所以我知道名字弄乱和外部“C”所以 但是当我将其包含在.c文件中时,由于\ifdef\uuucplusplus 因此,我最终制作了两份副本: #ifdef __cplusplus extern "C" { int isPrime(int64_t p); } #else int isPrime(int64_t p); #endif 有没有更好的方法来做到这一点。。。我考虑制作另一个标题名为proto
\ifdef\uuucplusplus
因此,我最终制作了两份副本:
#ifdef __cplusplus
extern "C"
{
int isPrime(int64_t p);
}
#else
int isPrime(int64_t p);
#endif
有没有更好的方法来做到这一点。。。我考虑制作另一个标题名为prototype.h,并将其包含在这两个地方。。。但是我有没有遗漏一些简单的东西呢?是的,有更好的方法。人们通常这样做:
#ifdef __cplusplus
extern "C"
{
#endif
int isPrime(int64_t p);
#ifdef __cplusplus
}
#endif
<>如果你想在C和C++中做一些不同的事情(比如说),那么你可以使用你的问题中的第二个语法。
#ifdef __cplusplus
extern "C"
{
#endif
int isPrime(int64_t p);
#ifdef __cplusplus
}
#endif
这样,您就可以扩展
intisprime(int64\tp)代码>任意分割而不在#ifdef
和#else
案例中重复。另一种方法如下
// intro
#ifdef __cplusplus
#define EXTERN_C extern "C"
#else
#define EXTERN_C
#endif
// content
EXTERN_C int isPrime(int64_t p);
// many other functions declared with EXTERN_C
通常,“简介”部分放在一些公共头文件中供大家使用
这种格式的优点是,每个声明都立即被视为extern“C”
。读者不必四处搜索可能的extern“C”{
// intro
#ifdef __cplusplus
#define EXTERN_C extern "C"
#else
#define EXTERN_C
#endif
// content
EXTERN_C int isPrime(int64_t p);
// many other functions declared with EXTERN_C