2

I'm trying to forward declare struct_A and use it within struct_B not as a pointer but as a structure. Within struct_B, I make reference to struct_B.

I can't seem to get it right - help? Here's my code:

struct type_A_t;
typedef struct type_A_t type_A_t;

typedef struct type_B_t {
    type_A_t a;
};

struct  type_A_t{
    void (*cb)(type_B_t *b1);
    void (*cb)(type_B_t *b2);
};

The error I get is:

error: field 'type_A_t' has incomplete type

1
  • another problem is that type_B_t is not defined Commented Dec 18, 2018 at 9:19

3 Answers 3

3

You can't do that. But in your example, since type_A_t only needs to know about pointers to type_B_t, why not switch it around like this?

typedef struct type_B_t type_B_t;
typedef struct type_A_t type_A_t;

struct  type_A_t {
    void(*cb)(type_B_t *b1);
    void(*cb)(type_B_t *b2);
};
typedef struct type_B_t {
    type_A_t a;
};
Sign up to request clarification or add additional context in comments.

Comments

0

That is not possible. To use a type as a member, the type's size must be known, so it must be fully defined. Otherwise, sizeof(struct type_B_t) would be unknown after its definition, which makes no sense.

Comments

0

I can't seem to get it right - help?

Because it cannot be done.

The compiler doesn't know the size of that struct.

A forward declaration is enough for pointers though:

typedef struct type_B_t {
    type_A_t a;  // error
    type_A_t* a; // OK
};

Of course, if in your real code, you can switch the order, as @Blaze's answer mention, then do that.

1 Comment

This is a C only question, there are no references.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.