Issue
I have defined these structures.
struct http_req {
struct http_req_line rl;
}
struct http_req_line {
enum method {
OPTIONS,
GET,
HEAD,
POST,
PUT,
DELETE,
TRACE,
CONNECT
} method;
enum uri_type {
ASTERISK,
ABSOLUTEURI,
ABS_PATH,
AUTHORITY
} uri_type;
union req_uri {
char asterisk[1];
char absoluteURI[256];
char abs_path[256];
char authority[256];
} req_uri;
char http_ver[16];
};
When I compile the file this header file is included in (which compiles fine on its own), gcc gives me this
request_types.h:2:23: error: field ‘rl’ has incomplete type
struct http_req_line rl;
But changing the 2nd line of the header to
struct http_req_line *rl;
gets rid of this error. What causes this error, and does changing that member to a pointer really fix the problem, or just hide it from the compiler?
Solution
At the point where the compiler sees:
struct http_req {
struct http_req_line rl;
}
there is no information about what a struct http_req_line
is. You need the structure definition for struct http_req
to appear after the definition of struct http_req_line
. You can use a pointer (to an incomplete type); you can't use a copy of the structure.
See the C11 standard §6.7.2.1 Structure and union specifiers:
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), …
Answered By - Jonathan Leffler