Rafael Botas
Rafael Botas

Reputation: 125

How to use a struct from another file?

I am trying to use an *.h named structures in other files like clube.c which will create an array from the struct defined as Clubes.

structures.h:

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

no matter what I do it just doesn't appear in my clubes.c

Note: already did the include "structures.h"

Once again thanks in advance, and if theres any info that I can give to help you help me just ask.

Upvotes: 2

Views: 11646

Answers (3)

Aleksandar Makragić
Aleksandar Makragić

Reputation: 1997

Keyword typedef just lets you define type, for example, typedef int whole_number this will create type whole_number and now you can use it as you would use int, whole_number x = 5; Same thing with structures. People use typedef on structures so they don't need to write struct Clubes:

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

And now you don't have to use struct Clubes x;, you can use clubes x; which is shorter and easier to write.

Extern keyword is giving you global linkage, and in this case it doesn't do anything.

Your question is a little bit confusing. If you want to create this structure, and then use it in other files you need to create header file:

#ifndef __CLUBES_H_
#define __CLUBES_H_ 1

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

#endif

Save this in one header file, for example clubes.h and then in some other c code where you want to use this structure you just include header with #include "clubes.h"

Upvotes: 4

hanumantmk
hanumantmk

Reputation: 661

I think you're confusing what some of these keywords do.

struct creates a new type. This doesn't create any instances of a type.

extern is for providing linkage for a global variable.

typedef is giving a new global name to an existing type.

/* 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... */
}

Upvotes: 1

user590028
user590028

Reputation: 11738

Perfect use for header files

/* 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];

Upvotes: 0

Related Questions