且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在C ++中向前声明静态C结构体实例

更新时间:2022-12-24 09:08:02

这似乎与Josh的答案有相似的效果,但复杂性较低:

This seems to have a similar effect to Josh's answer, but with less complexity:

#ifdef __cplusplus
namespace {
    extern Foo f1;
    extern Foo f2;

    Foo f1 = {1, &f2};
    Foo f2 = {2, &f1};
}
#else
    static Foo f1;
    static Foo f2;

    Foo f1 = {1, &f2};
    Foo f2 = {2, &f1};
#endif

当编译为C ++时,f1和f2的extern定义所述目标文件具有外部可链接符号;然而,因为它们在匿名命名空间内,所以符号被以不与另一个翻译单元的符号冲突的方式被破坏。

When compiled for C++, the extern definitions for f1 and f2 are exposed in the object file with an externally linkable symbol; however, because they are inside an anonymous namespace the symbols are mangled in such a way that they will not conflict with symbols from another translation unit.

使用宏魔法,你可以设置因此,只有一个地方,f1和f2被声明和定义,但如果这是机械生成的,可能没有太多理由这样做。

With macro magic you could set things up so there's only one place where f1 and f2 are declared and defined, but if this is being generated mechanically there's probably not much reason to do that.

有点像:

#ifdef __cplusplus
#define START_PRIVATES namespace {
#define END_PRIVATES   }
#define PRIVATE extern
#else
#define START_PRIVATES 
#define END_PRIVATES   
#define PRIVATE static
#endif

START_PRIVATES
    PRIVATE Foo f1;
    PRIVATE Foo f2;

    Foo f1 = {1, &f2};
    Foo f2 = {2, &f1};
END_PRIVATES