The Pointer The Pointer - 1 year ago 85
C Question

Declaring an extern struct template in header file for global use in c files

My goal is to declare and define a single structure template in my header file. I then wish to use this template to declare and define individual structures in my c files.

This is a rough example of what I'm aiming for:

header file

#include <bool.h>

extern struct options
extern bool aflag;
extern bool cflag;
extern bool dflag;
} option1;

c file

#include "header.h"

struct options option1;
void function(void)
option1.aflag = true;
option1.cflag = true;
option1.dflag = true;

I want this to result in the structure
being globally visible. The global contents should be
aflag = true
cflag = true
, and
dflag = true

When I say global, I mean that the contents
aflag = true
cflag = true
, and
dflag = true
(defined in another c file) should now be usable in yet a second c file if I wish. The only reference being the header file with the structure.

However, as I expected, this example contains multiple errors. I have only recently learned the basics of structures and am unsure of how to achieve exactly what I'm looking for, so it would be helpful if someone could explain how this effect can be achieved, possibly with code examples.

Thank you.

Answer Source

When you declare a structure you define a type.

If you want a struct to be globally visible then you need tp define a variable not a type.

So you can do something like this in your foo.h header file:

struct foo {
    int bar;
    double baz;

extern struct foo globally_visible_foo_yay;

And then in the foo.c file you want:

#include "foo.h"
struct foo globally_visible_foo_yay = {.bar = 42, .baz = 42.0};

And in some other C file you can then use the globally visible struct by including the header.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download