Home > Enterprise >  C Header Based Configuration Not Working as Expected
C Header Based Configuration Not Working as Expected

Time:02-24

In my C code, I want to have some configurations that can be set prior to including my header file. However, defining it before or after my include in the main source file is always using it with the default value (even if I set it before my include).

Below are my source files.

header.h

#ifndef header_h
#define header_h

#ifndef MY_DEBUG
#  define MY_DEBUG 0
#endif

void print(int*, int);

#endif /* header_h */

header.c

#include "header.h"
#include <stdio.h>

void print(int* data, int count) {
    if(MY_DEBUG) {
        printf("List Type: int - Count: %d\n", count);
    }

    printf("[");

    int i;
    for(i = 0; i < count;   i) {
        if(i > 0) {
            printf(", ");
        }

        printf("%d", data[i]);
    }

    printf("]\n");
}

main.c

#define MY_DEBUG 1

#include "header.h"

// #define MY_DEBUG 1

int main(int argc, const char** argv) {
    int list[5] = { 1, 2, 3, 4, 5 };
    int count = 5;

    print(list, count);

    return 0;
}

The output is always [1, 2, 3, 4, 5].

Is this not the correct way to use the configuration in the headers or am I missing something?

I don't want to pass the defines when compiling, I want to be able to do them using #define in my code.

EDIT: I tried something now, I guess now I know why it wasn't working. I think it's because my source file, when compiled, before main MY_DEBUG wasn't defined yet so it took the default value. I tried to move the implementation to the header and remove the header.c altogether and it seems to have worked when defining MY_DEBUG before my include. But this is not my case here, is there some kind of workaround for it? Maybe define the configurations as variables in a separate header/source files and have their own getters and setters?

CodePudding user response:

Adding #define MY_DEBUG 1 in main.c changes the value of the macro in the translation unit containing main.c and header.h It does not change it in the translation using containing header.c and header.h.

You would either need to add the macro separately in header.c, or simply change it in header.h.

CodePudding user response:

You have to compile header.c with (or without) the -DMY_DEBUG option. It is a separate translation unit (TU) from main.c, and the setting of MY_DEBUG in main.c does not affect the code in header.c.

  • Related