Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice to use extern struct or extern pointer to struct?

Say I have 3 files: file1.c, file2.c and globals.h. file1.c and file2.c both include globals.h. file1.c contains a struct that file2.c needs to use. Is it better to make the struct itself extern or create a pointer to the struct and make that pointer extern in globals.h?

like image 334
user1172282 Avatar asked Feb 25 '26 00:02

user1172282


1 Answers

If I understand correctly and your "a struct" is supposed to be a global object (which is a questionable design choice), then I'd do it like this:

foo.h:

typedef struct foo_struct
{
    /* ... */
} foo;

extern foo the_foo;

foo.c: [If you like and if it makes sense, you can merge this into file1.c.]

#include "foo.h"

foo the_foo = { /* ... */ };

file1.c and file2.c:

#include "foo.h"
#include "global.h"

/* ... */
like image 159
Kerrek SB Avatar answered Feb 26 '26 13:02

Kerrek SB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!