defining static const structs

dudico picture dudico · Mar 29, 2009 · Viewed 36.9k times · Source

This question is related to Symbian OS yet I think that C/C++ veteran can help me too. I'm compiling an open source library to Symbian OS. Using a GCCE compiler it compiles with no errors (after some tinkering :) ). I changed compiler to ARMV5 and now I have multiple errors with the definitions of static const structs, for example: I have a struct:

typedef struct Foos{
    int a;
    int b;
} Foos;

And the following definition of a const struct of type Foos

static const Foos foo = {
    .a = 1,
    .b = 2,
};

GCCE has no problem with this one and ARMV5 goes "expected an expression" error on the ".a = 1, .b = 2,". From what I googled regarding this I reckon that this method should be legal in C but illegal in C++, if that's the case then what are the possibilities for declaring const structs in C++ ? If that's not the case then any other help will be appreciated.

Thanks in advance :)

Answer

Daniel Sloof picture Daniel Sloof · Mar 29, 2009
static const struct Foos foo = { 1, 2 };

Compiles with both g++ and gcc.

You could ofcourse, as onebyone points out, define a constructor:

typedef struct Foos {
    int a;
    int b;
    Foos(int a, int b) : a(a), b(b) {}
};

Which you would initalize like so:

static const struct Foos foo(1, 2);