如何检测 C 代码(需要 'extern C')是否在 C++ 中编译
How to detect if C code (which needs 'extern C') is compiled in C++
我有一个 C 头文件作为 C++ 库的一部分。
此 C 头文件只有在 C 编译器或 extern "C" { ... }
块中由 C++ 编译器编译才有意义,否则会发生未解决的 link 错误。
我想添加一个块,例如:
#ifdef __cplusplus
#error "Compiling C bindings with C++ (forgot 'extern \"C\"'?)"
#endif
在 C 头文件中,但不幸的是 __cplusplus
宏也在 extern "C" { ... }
块中定义。
还有其他方法可以正确检测这种情况吗?
通常的做法是不要求客户端代码将您的 header 包装在 extern "C"
中,而是您自己有条件地这样做。例如:
#ifdef __cplusplus
extern "C" {
#endif
// Header content
#ifdef __cplusplus
}
#endif
这样客户端代码会自动更正,除了包含 header.
之外无需执行任何操作
我有一个 C 头文件作为 C++ 库的一部分。
此 C 头文件只有在 C 编译器或 extern "C" { ... }
块中由 C++ 编译器编译才有意义,否则会发生未解决的 link 错误。
我想添加一个块,例如:
#ifdef __cplusplus
#error "Compiling C bindings with C++ (forgot 'extern \"C\"'?)"
#endif
在 C 头文件中,但不幸的是 __cplusplus
宏也在 extern "C" { ... }
块中定义。
还有其他方法可以正确检测这种情况吗?
通常的做法是不要求客户端代码将您的 header 包装在 extern "C"
中,而是您自己有条件地这样做。例如:
#ifdef __cplusplus
extern "C" {
#endif
// Header content
#ifdef __cplusplus
}
#endif
这样客户端代码会自动更正,除了包含 header.
之外无需执行任何操作