문제

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.

도움이 되었습니까?

해결책

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);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top