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

后端 未结 3 1025
夕颜
夕颜 2021-02-05 12:20

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;
    do         


        
3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-05 13:16

    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.

提交回复
热议问题