tags:

views:

1682

answers:

4

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 :)

+8  A: 
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);
Daniel
Thanks! Removing the field names worked.
dudico
+3  A: 

The dot style notation is I think valid in ANSI C99. It is not valid is ANSI C89. Almost all C compilers have not implemented C99.

Blank Xavier
+4  A: 

That's legal C99, but not legal C89 or C++. Presumably you're compiling this as C++, so if you use compiler options to enforce standards-compliance, then GCCE will reject it too.

You can do foo = {1, 2}; in C or C++. Obviously you lose the benefit of the field names being right there: you have to rely on getting the order right.

Another good option in C++ is to define a constructor for your struct, and initialize with static const Foos foo(1,2);. This does prevent the struct being POD, however, so you can't make the same assumptions about its representation in memory.

Steve Jessop
+2  A: 

Just a note that writable static data is not supported in DLL's on some versions of Symbian. It may not affect what you are doing as your examples are const or you may be only supporting Symbian v8.1b or later.

I thought I would point it out as I fell into that trap once.

Quote from the link above:

Support for global writeable static data on Symbian OS

Symbian OS supports global writeable static data in EXEs on all versions and handsets.

Versions of Symbian OS based on the EKA2 kernel (8.1b and later) support WSD in DLLs on target hardware. Versions 8.1a and earlier, based on the EKA1 kernel, do not support global WSD in DLLs.

Shane Powell
Yea, I am aware of the limit on static data in pre 8.1 OS, I'm using the library for 9.1 and later. Thanks for making that important note anyway!
dudico