Using a struct in a header file “unknown type” error

偶尔善良 提交于 2019-12-03 02:03:38

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.

If you have to define a new type, you have to write:

typedef struct {

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

Then you can use georeg_val as a new type.

Defining a struct type (on this example, a binary search tree struct):

struct tree { 
  int info;
  struct tree *left;
  struct tree *right;
} 

typedef struct tree treeNode;

Declaring a function eg.:

treeNode *insertElement(treeNode *treeA, int number);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!