Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

variable redefinition, embedded c

I'm working on an embedded c project and am having issues with global variable redefinition.

I've split up the function declarations and definitions into a handful of .h and .c files. Many of these functions need access to global variables, which are defined in global_vars.h. Therefore, at the beginning of the header files, inside the #ifndef, #define section, "global_vars.h". If I don't, as you might imagine I get a bunch of undefined variable errors.

However, even though global_vars.h has the #ifndef _GLOBAL_VARS_H_ #define... #endif, I get redefinition errors for all the global variables. My guess is that when the linker tries link the various object files, it sees the redefinition due to the #include "global_vars.h" in all the "blah_blah.h" files. It was my understanding, though, that the #ifndef... takes care of this issue.

Is there something I'm overlooking?

Thanks in advance

like image 351
Trey Avatar asked Oct 14 '25 17:10

Trey


1 Answers

The linker never sees anything in the global_vars.h file, ever, unless -- bad news! -- some of the globals are actually defined in that file. global_vars.h should hold only declarations of those global variables, never (well, almost never) their definitions.

In global_vars.h, you should have declarations like:

extern int some_global;

You are not allowed to have:

int some_global;

If you have definitions in global_vars.h then, yes, they'll be multiply defined at link time because each of the .c files that #includes global_vars.h will have its own definition of each defined variable.

All of the definitions of the extern globals must be in some .c file, for sure. Usually it doesn't matter which .c file. Often all of the global-variable definitions are in a file called (surprise!) global_vars.c.

So make sure there aren't any global-variable definitions in global_vars.h and you'll be in good shape.

like image 77
Pete Wilson Avatar answered Oct 17 '25 09:10

Pete Wilson



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!