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

后端 未结 3 1024
夕颜
夕颜 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条回答
  • 2021-02-05 13:12

    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);
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-05 13:25

    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.

    0 讨论(0)
提交回复
热议问题