c - how to create a config object

Viewed 266

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

2 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).

Create a config.c file that you will add to your compilation with the following:

#include <config.h> // or "config.h"
config_t config_instance = {
        .output = "default output",
        .output_display = "default display",
};

And extern the varaible in your config.h file :

extern config_t config_instance;

Or better. Let's create a function that will allow access to your config, so we can track and validate changes to it. Create config.c like this:

#include <config.h> // or "config.h"
static config_t config_instance = {
        .output = "default output",
        .output_display = "default display",
};

const config_t *config_get(void) {
     return &config_instance;
}

int config_set(const config_t *newconfig) {
     if (/* check if newconfig is valid etc. */) {
          return -1; // return error number
      }
      config_instance = *newconfig;
      return 0; // success in changing config
 }

and export the functions by adding in your config.h file:

 const config_t *config_get(void);
 int config_set(const config_t *newconfig);
Related