如何编写可在C ++程序中使用的C头文件?

时间:2012-09-22 23:24:42

标签: c++ c macros

  

可能重复:
  How to check (via the preprocessor) if a C source file is being compiled as C++ code

我正在尝试找到一个标准宏来测试头文件是编译为C还是C ++。这样做的目的是标题可以包含在C或C ++代码中,并且必须根据具体情况略有不同。具体做法是:

在C中,我需要这个代码:

extern size_t insert (const char*);

在C ++中,我需要这个代码:

extern "C" size_t insert (const char*);

此外,有没有办法避免在标题中的每个声明周围放置#ifdef?

2 个答案:

答案 0 :(得分:27)

将C头文件括起来是正常的,因此可以在C ++程序中使用它们。检查系统头文件,例如stdio.h,您可能会看到:

#ifdef __cplusplus
extern "C" {
#endif

...

#ifdef __cplusplus
}
#endif

答案 1 :(得分:15)

答案是使用宏__cplusplus。在这种情况下,最直接的方法是:

extern
#ifdef __cplusplus
"C"
#endif
size_t insert (const char*);

这个宏是C ++标准的一部分。