PinkElephantsOnParade
PinkElephantsOnParade

Reputation: 6592

Nesting Structs in C

I'm a noob at C and need some help getting my code to...welll...do anything. I have the following put into a .h file.

typedef struct
{
    int active; 
    int dead;
    ucontext_t t;
    struct node *link;
}gtthread_t;

struct node{
   struct gtthread_t thread;
};

typedef struct
{
int rubic;
}gtthread_mutex_t;

This is in a .h file... a .h file where I have had to #include ucontext.h ... which I know I am also not supposed to do... but it's the only way I can access ucontext_t, I find.

So, my error here is "field thread has incomplete type".

Why? What does that even mean? And how can I possible NOT import ucontext.h if I want to declare structs with that kind of data in the .h file?

Upvotes: 1

Views: 162

Answers (3)

unwind
unwind

Reputation: 399763

The ucontext.h header only pre-declares the ucontext_t type. You're only supposed to use pointers to it, since its size is not known. Change your code to:

ucontext_t *t;

and you will be fine. Notice that all the functions in the ucontext.h header use such pointers to refer to contexts. This is common in C API design, since it allows the representation to be hidden inside the API's implementation, which is nice.

Upvotes: 1

John Bode
John Bode

Reputation: 123448

One problem is that struct node has not been declared yet, so the gtthread_t type cannot be completed.

typedef struct
{
    int active; 
    int dead;
    ucontext_t t;
    struct node *link;        
}gtthread_t;

struct node{
   struct gtthread_t thread;
};

You'll need a forward declaration of struct node:

struct node;

typedef struct
{
    int active; 
    int dead;
    ucontext_t t;
    struct node *link;        
}gtthread_t;

struct node{
   struct gtthread_t thread;
};

Try that and see if it makes a difference.

Upvotes: 0

Sergey L.
Sergey L.

Reputation: 22542

Has nothing to do with your other include. This has to do with the fact that your first struct is anonymous and has a type name gtthread_t. C unlike C++ distinguishes between gtthread_t and struct gtthread_t.

Either name the struct:

struct gtthread_t
{
    int active; 
    int dead;
    ucontext_t t;
    struct node *link;
};

Or change the type name to the typedef:

struct node{
   gtthread_t thread;
};

Upvotes: 2

Related Questions