Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typedef stuct with forward declaration in C

I have something like:

typedef struct Data DATA, *DATA_PTR;
typedef struct Units UNITS, *UNITS_PTR;

struct Data
{
    double miscData;
    UNITS units;
};

struct Units
{
    double x[2];
    double y[2];
    double z[2];
};

in my project_typedef.h file.

In another file, I have something like:

void fileInput(DATA_PTR data)
{
     //usual declarations and other things
     data->miscData = 0; //Works!
     data->units.x[0] = 5; //Doesn't work
     //etc...
}

However, this doesn't work since units is declared after data in project_typedef.h (if I switch the order it works). The error that i get is "left of '.x' must have struct/union type". I thought that the forward declaration would fix this issue. Why not?

like image 251
user1007692 Avatar asked Nov 16 '11 18:11

user1007692


People also ask

Can I forward declare a typedef?

But you can't forward declare a typedef. Instead you have to redeclare the whole thing like so: typedef GenericValue<UTF8<char>, MemoryPoolAllocator<CrtAllocator> > Value; Ah, but I don't have any of those classes declared either.

Can you forward declare a struct?

In C++, classes and structs can be forward-declared like this: class MyClass; struct MyStruct; In C++, classes can be forward-declared if you only need to use the pointer-to-that-class type (since all object pointers are the same size, and this is what the compiler cares about).

What is forward declaration in C?

As others stated before, a forward declaration in C/C++ is the declaration of something with the actual definition unavailable. Its a declaration telling the compiler "there is a data type ABC".

How do you declare a variable in a typedef struct?

The purpose of typedef is to give a name to a type specification. The syntax is: typedef <specification> <name>; After you've done that, you can use <name> much like any of the built-in types of the language to declare variables.


1 Answers

When you define Data, all members must be complete types. Since UNITS isn't a complete type at that point, this doesn't work. (By contrast, UNITS_PTR would be fine, since pointers to incomplete types are complete types.)

Simply put the Units definition above the Data definition and you should be fine.

(As @cnicutar already noted, you're also using the array x wrong.)

like image 81
Kerrek SB Avatar answered Oct 14 '22 07:10

Kerrek SB