Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static initialisation of a char array in a constant struct from C to C++

Tags:

I have some existing code in C:

extern const struct sockaddr_un addr =
{
    .sun_family = AF_UNIX,
    .sun_path   = "myreallylongpath"
};

Where sun_path is a character array.

This used to compile fine as C in an older version of GCC. I have now converted it to C++ and am using GCC v4.7.2. I keep getting the error:

"C99 designator 'sun_path' outside aggregate intializer"

Is it not possible to do what I am doing in C++, or is the syntax different from the old C?

like image 234
Joe Avatar asked Oct 04 '13 09:10

Joe


People also ask

How to initialise struct in C?

Structure members can be initialized using curly braces '{}'. For example, following is a valid initialization.

How initialize struct?

When initializing a struct, the first initializer in the list initializes the first declared member (unless a designator is specified) (since C99), and all subsequent initializers without designators (since C99)initialize the struct members declared after the one initialized by the previous expression.

How to initialize union?

An initializer for a structure is a brace-enclosed comma-separated list of values, and for a union, a brace-enclosed single value. The initializer is preceded by an equal sign ( = ).


1 Answers

Designated initializers were introduced in C99, GCC also supports them as an extension in GNU89, but not in C++.

So you need to use the C89 style, which is also supported in C++. Since the struct has only these two fields:

extern const struct sockaddr_un addr =
{
    AF_UNIX,
    "myreallylongpath"
};

Reference: Designated Initializers

like image 71
Yu Hao Avatar answered Sep 20 '22 10:09

Yu Hao