Fer
Fer

Reputation: 1992

cannot declare struct member within a structure in c

I want to declare a structure value in a different structure definition in header file. So I have done the following in header file. But compiler gives me the error message field myStructMember has incomplete type

in A.h header file:

struct My_A{
    int value;
};

In B.h header file:

struct My_A; // forward declaration
struct My_B
    {
        struct My_A myStructMember; // error is here!
        int differentValue;
    };

Is it possible to declare a struct member within a structure declarations?

EDIT: My_A and My_B are declarated in different header file.

EDIT 2: When I add include "A.h" in B.h, then it works. Does it make any problem? In B.h header file:

include "A.h" // added this line insead of forward declaration
struct My_B
    {
        struct My_A myStructMember; // not any error anymore
        int differentValue;
    };

Upvotes: 0

Views: 276

Answers (2)

Oliver Matthews
Oliver Matthews

Reputation: 7803

Not without # including A.h in B.h (or before B.h every time it is referenced - when the compiler parses My_B otherwise it lacks the information required to determine the size of My_A. You could use a pointer instead, but that gains all the overhead of handling them.

If you are just trying to achieve abstraction / details hiding, then you could change your forward declaration of My_A so that it is now a struct of the correct size (using a char array, for instance). Then you must make sure that nothing includes both A.h and B.h as that will cause a compiler error. Oh, and really make sure you get the size right or weird stuff will happen. There are ways to ensure this is correct using macro assertions.

e.g. make B.h

struct My_A{
    char hidden_data[4];
};

struct My_B
{
    struct My_A myStructMember; 
    int differentValue;
};

Upvotes: 1

aragaer
aragaer

Reputation: 17848

The error is what it says - you can't use struct until you has it's complete type. You simply don't know its size at that point. Forward declaration won't help here.

Alternatively you can use pointer to struct. Pointer size is known.

Upvotes: 1

Related Questions