问题
I have an issue with SDCC. My code (which I am attempting to port from another compiler) uses structs with flexible array members. However, when I try to compile the following code:
/** header of string list */
typedef struct {
int nCount;
int nMemUsed;
int nMemAvail;
} STRLIST_HEADER;
/** string list entry data type */
typedef struct {
int nLen;
char str[];
} STRLIST_ENTRY;
/** string list data type */
typedef struct {
STRLIST_HEADER header;
STRLIST_ENTRY entry[];
} STRLIST; // By the way, this is the line the error refers to.
int main()
{
return 0;
}
SDCC gives the following error:
$ sdcc -mz80 -S --std-c99 test.c
test.c:18: warning 186: invalid use of structure with flexible array member
test.c:18: error 200: field 'entry' has incomplete type
What gives? This code compiles just fine in gcc, not to mention the other z80 compiler I'm using.
EDIT: I found this SDCC bug which seems to be related. Could someone explain if it is and how?
回答1:
SDCC is right there, and gcc-4.6.2 does not compile it "just fine" either. Well, if you ask it to adhere to the standard pedantically.
Compiling with -std=c99 -pedantic
(or -std=c1x -pedantic
), gcc emits
warning: invalid use of structure with flexible array member
and clang-3.0 behaves similarly, its warning is slightly more informative:
warning: 'STRLIST_ENTRY' may not be used as an array element due to flexible array member
The standard prohibits that in 6.7.2.1 (3):
A structure or union shall not contain a member with incomplete or function type (hence, a structure shall not contain an instance of itself, but may contain a pointer to an instance of itself), except that the last member of a structure with more than one named member may have incomplete array type; such a structure (and any union containing, possibly recursively, a member that is such a structure) shall not be a member of a structure or an element of an array.
(emphasis is mine)
gcc and clang allow having struct
s with flexible array members as members of struct
s or arrays as an extension. The standard prohibits that, so code using that is not portable, and every compiler is within its rights to reject the code.
The linked issue is not relevant, it is about not giving a warning if a struct
with a flexible array member is instantiated as an automatic, which isn't allowed per the standard (but accepted by SDCC and others as an extension).
回答2:
Think about why this is an error.
STRLIST_ENTRY is of an unknown size because str[] is variable length.
STRLIST contains a variable length array of STRLIST_ENTRY.
In memory the array is a sequence of STRLIST_ENTRY laid out immediately after one another.
Since the elements of that are of an unknown size, how is it possible to know the offset an index points to?
char str[] should either be given a fixed size, or made a char* to a string outside of the array.
来源:https://stackoverflow.com/questions/14352229/sdcc-not-accepting-code