Using a struct in a header file "unknown type" error

dead_jake picture dead_jake · Apr 30, 2012 · Viewed 56.7k times · Source

I am using Kdevelop in Kubuntu. I have declared a structure in my datasetup.h file:

#ifndef A_H
#define A_H

struct georeg_val {

    int p;
    double h;
    double hfov;
    double vfov;
};

#endif

Now when I use it in my main.c file

int main()
{
    georeg_val gval;

    read_data(gval); //this is in a .cpp file

}

I get the following error:

georeg_chain.c:7:3: error: unknown type name 'georeg_val'

(This is in the georeg_val gval; line)

I would appreciate if anyone could help me resolve this error.

Answer

Agnius Vasiliauskas picture Agnius Vasiliauskas · Apr 30, 2012

In C one has two possibilities to declare structure:

struct STRUCT_NAME {} ;

or

typedef struct {} STRUCT_ALIAS;

If you use first method (give struct a name) - you must define variable by marking it explicitly being a struct:

struct STRUCT_NAME myStruct;

However if you use second method (give struct an alias) then you can omit struct identifier - compiler can deduce type of variable given only it's alias :

STRUCT_ALIAS myStruct;

Bonus points: You can declare struct with both it's name and alias:

typedef struct STRUCT_TAG {} STRUCT_TAG;
// here STRUCT_NAME == STRUCT_ALIAS

Then in variable definition you can use either first or second method. Why both of two worlds is good ? Struct alias lets you to make struct variable definitions shorter - which is a good thing sometimes. But struct name let's you to make forward declarations. Which is indispensable tool in some cases - consider you have circular references between structs:

struct A {
  struct B * b;
}
struct B {
  struct A * a;
}

Besides that this architecture may be flawed - this circular definition will compile when structs are declared in the first way (with names) AND struct pointers are referenced explicitly by marking them as struct.