如何使用另一个文件中的结构?

How to use a struct from another file?

我正在尝试在其他文件中使用 *.h 命名结构,例如 clube.c,它将根据定义为 Clubes 的结构创建一个数组。

structures.h:

extern typedef struct Clubes{
 char *codClube;
 char *nome;
 char *estadio;
};

无论我做什么,它都不会出现在我的 clubes.c

注意:已经包含 "structures.h"

再次提前致谢, 如果有任何信息可以帮助你帮助我,请问。

头文件的完美使用

/* put this in clube.h */
struct Clubes{
 char *codClube;
 char *nome;
 char *estadio;
};

/* put this in clube.c */
#include "clube.h"

struct Clubes myarray[5];

我认为您混淆了其中一些关键字的作用。

struct 创建一个新类型。这不会创建类型的任何实例。

extern 用于为全局变量提供链接。

typedef 正在为现有类型赋予新的全局名称。

/* clube.h */

/* define and declare the Clubes struct */
struct Clubes {
    char* codClube;
    char* nome;
    char* estadio;
}

/* typedef the Clubes struct.
 * Now you can say struct Clubes or Clubes_t in your code.
 */
typedef struct Clubes Clubes_t;

/* Now you've created global linkage for my_clubes.
 * I.e. two cpp files could both modify it
 */
extern struct Clubes my_clubes[2];



/* clube.c */

#include "clube.h"

/* Now you've got storage for my_clubes */
Clubes_t my_clubes[2];


/* some_other.c */

#include "clube.h"

void fun() {
    my_clubes[0].codClube = "foo";
    /* etc... */
}

关键字 typedef 只允许您定义类型,例如,typedef int whole_number 这将创建类型 whole_number,现在您可以像使用 int 一样使用它, whole_number x = 5; 与结构相同。人们在结构上使用 typedef 所以他们不需要写 struct Clubes:

typedef struct Clubes{
 char *codClube;
 char *nome;
 char *estadio;
} clubes;

而且现在你不必使用struct Clubes x;,你可以使用clubes x;,它更短也更容易写。

Extern 关键字为您提供了全局链接,在这种情况下它没有任何作用。

你的问题有点令人费解。如果你想创建这个结构,然后在其他文件中使用它你需要创建头文件:

#ifndef __CLUBES_H_
#define __CLUBES_H_ 1

struct Clubes{
 char *codClube;
 char *nome;
 char *estadio;
} clubes;

#endif

将其保存在一个头文件中,例如 clubes.h,然后在您想要使用此结构的其他 c 代码中,您只需将头文件包含在 #include "clubes.h" [=24 中=]