Union initialization in C++ and C

戏子无情 提交于 2019-12-05 08:44:39

问题


I have built a working C library, that uses constants, in header files defined as

typedef struct Y {
  union {
    struct bit_field bits;
    uint8_t raw[4];
  } X;
} CardInfo;

static const CardInfo Y_CONSTANT = { .raw = {0, 0, 0, 0 } };

I know that the .raw initializer is C only syntax.

How do I define constants with unions in them in a way such that I can use them in C and C++.


回答1:


I had the same problem. For C89 the following is true:

With C89-style initializers, structure members must be initialized in the order declared, and only the first member of a union can be initialized

I found this explanation at: Initialization of structures and unions




回答2:


I believe that C++11 allows you to write your own constructor like so:

union Foo
{
    X x;
    uint8_t raw[sizeof(X)];

    Foo() : raw{} { }
};

This default-initializes a union of type Foo with active member raw, which has all elements zero-initialized. (Before C++11, there was no way to initialize arrays which are not complete objects.)




回答3:


I decided to choose the following path.

  • Do not use .member initialization.
  • do nost use static const struct Foobar initialization of members

Instead declare the global variable:

extern "C" {
  extern const struct Foobar foobar;
}

and initialize it in a global section:

struct Foobar foobar = { 0, 0, 0, 0 };

and instead of bugging the C++ compiler with modern ANSI C99 syntax I let the linker do the work be demangling C symbols.



来源:https://stackoverflow.com/questions/11555702/union-initialization-in-c-and-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!