如何检测C代码(需要'extern C')是否是用C ++编译的

问题描述 投票:46回答:1

我有一个C头作为C ++库的一部分。

这个C头只能由C编译器或extern "C" { ... }块中的C ++编译器编译,否则会发生未解决的链接错误。

我想添加一个块,如:

#ifdef __cplusplus
#error "Compiling C bindings with C++ (forgot 'extern \"C\"'?)"
#endif

在C标题中,但不幸的是__cplusplus宏也定义在extern "C" { ... }块内。

有没有其他方法可以正确检测这种情况?

c++ c extern
1个回答
101
投票

通常的做法是不要求客户端代码在extern "C"中包装你的标题,而是要自己有条件地这样做。例如:

#ifdef __cplusplus
extern "C" {
#endif

  // Header content

#ifdef __cplusplus
}
#endif

这样,客户端代码会自动更正,而不会执行除头部之外的任何操作。

© www.soinside.com 2019 - 2024. All rights reserved.