我有一个C头作为C ++库的一部分。
这个C头只能由C编译器或extern "C" { ... }
块中的C ++编译器编译,否则会发生未解决的链接错误。
我想添加一个块,如:
#ifdef __cplusplus
#error "Compiling C bindings with C++ (forgot 'extern \"C\"'?)"
#endif
在C标题中,但不幸的是__cplusplus
宏也定义在extern "C" { ... }
块内。
有没有其他方法可以正确检测这种情况?
通常的做法是不要求客户端代码在extern "C"
中包装你的标题,而是要自己有条件地这样做。例如:
#ifdef __cplusplus
extern "C" {
#endif
// Header content
#ifdef __cplusplus
}
#endif
这样,客户端代码会自动更正,而不会执行除头部之外的任何操作。