Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c - how to create a config object

Tags:

c

config

I want to create a config object that can be used anywhere in my c program.

What would be the best practice to do so?

Currently, I have a config.h that looks like this:

#define OUTPUT 0
#define OUTPUT_DISPLAY 0
#define OUTPUT_WIDTH 1920
#define OUTPUT_HEIGHT 1080

typedef struct {
        const char *output
        const char *output_display;
        int output_width;
        int output_height;
} config_t;

Would I create a config_t instance named config or something in the header file?

Thanks

like image 909
yasgur99 Avatar asked Nov 18 '25 02:11

yasgur99


1 Answers

You declare a global object in the header file:

extern config_t global_config;

and then define it in some suitable .c file:

config_t global_config;

If you were to define the config variable in the header file, the linker would complain that multiple instances of global_config exist, as a new instance would get created with each import (assuming your project has multiple .c files).

like image 158
Henning Koehler Avatar answered Nov 20 '25 18:11

Henning Koehler



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!