This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

Declaration of global variables in one header file

Hello everyone,

I'm trying to split the C source code of one file into nearly 10 different. It does not work properly due to global variables declared in one header file but used in more than one C files. Compiling of such a project works fine but the linking errors L104 and L118 occur.

My question: How can I prevent this errors without creating one header file for every C file?

My idea is the following, but it is complicated and additionally unsure if it works:

#ifdef CPVAR
extern unsigned char global_var1;
extern unsigned int global_var2;
extern unsigned long global_var3;
#elseif
unsigned char global_var1;
unsigned int global_var2;
unsigned long global_var3;
#define CPVAR
#endif

Maybe one of the experts knows a less complicated opportunity to prevent (these) linker errors.

Parents
  • erik,

    Wow... I guess I totally missed your point. My apologies. Yes, I think when you use that particular method, that things end up being fairly readable, and I personally like it better than having global variables smattered at the top of each C file.

    Nonetheless, I do find that things I write tend to devolve into ugliness when I'm doing C51 code with this method. For instance, I almost always need to have some variables located with the _at_ keyword, which leads to the following sort of construct:

    #ifdef DEFINEGLOBALSHERE
    #define GLOBAL
    unsigned char somespecialvar _at_ 0x0200;
    #else
    #define GLOBAL extern
    extern unsigned char somespecialvar;
    #endif
    
    GLOBAL unsigned char somenormalvar;
    

    and so forth. Then, if I'm unlucky enough to need to initialize a global where it's defined, I have to do it similarly. Anyway... I guess my point is just that it's useful, but will be extremely ugly if you're not careful with it.

Reply
  • erik,

    Wow... I guess I totally missed your point. My apologies. Yes, I think when you use that particular method, that things end up being fairly readable, and I personally like it better than having global variables smattered at the top of each C file.

    Nonetheless, I do find that things I write tend to devolve into ugliness when I'm doing C51 code with this method. For instance, I almost always need to have some variables located with the _at_ keyword, which leads to the following sort of construct:

    #ifdef DEFINEGLOBALSHERE
    #define GLOBAL
    unsigned char somespecialvar _at_ 0x0200;
    #else
    #define GLOBAL extern
    extern unsigned char somespecialvar;
    #endif
    
    GLOBAL unsigned char somenormalvar;
    

    and so forth. Then, if I'm unlucky enough to need to initialize a global where it's defined, I have to do it similarly. Anyway... I guess my point is just that it's useful, but will be extremely ugly if you're not careful with it.

Children