chanzerre
chanzerre

Reputation: 2429

Declaration of structures in multiple files

If I include the declaration of the part structure(for example) into two different files, will part variables in one file be of the same type as part variables in the other file?

Upvotes: 0

Views: 160

Answers (1)

Barmar
Barmar

Reputation: 780994

Yes, they're of the same type if the declarations are structurally the same. If this weren't true, it wouldn't be possible to call library functions that use structure parameters, since the caller and callee are in different files.

The declarations don't have to be literally the same. As long as they specify the same types in the same order, things like member names and the name of the struct type don't have to match. So if you do:

file1.c:

struct {
    int i;
    char c;
} var1;

and in file2.c:

typedef struct newstruct {
    int v1;
    char v2;
} newstruct_t;
newstruct_t var2;

then var1 and var2 are of the same type.

The full details are a bit more complex, but this is a useful approximation.

However, programming like this will be confusing. If you intend to share a type between files, you should put the declaration in a header file, and #include it in all the source files that use it.

Upvotes: 3

Related Questions