We have a few global variables that we want to use in both user_routines.c and tracking.c. We can not seem to declare and access them in a way that the compiler likes. We either get an error saying multiple definitions, or not defined. I’ve tried defining the var in a globals.h and including that in both .c files, but that doesn’t work. I’ve tried adding extern declarations in my .c files, but no dice there either. I’ve tried about every combo of declaring in .c and .h files, with and without externs but nothing seems to work. Anybody know what my problem is?
define the var as:
extern mytype myvar;
in each file accessing it, except one.
Then, in ONLY ONE file (the only without an extern declaration), declare the variable normally:
mytype myvar;
See http://www.crasseux.com/books/ctutorial/External-variables.html
I’ve tried this, but it won’t work. In a file globals.h, I have the following:
int myvar;
Then, in user_routines.c I have:
#include “globals.h”
extern int myvar;
I do the same thing in tracking.c, with the include and extern declaration but I get the following linker error when I try to compile:
symbol ‘myvar’ has multiple definitions
I access the variable inside the default_routine function, and in another function in the tracking.c file. I’ve tried declaring it both inside the functions, and at the top of the .c file outside of any function, but below my preprocessor directives. Nothing seems to work. Everything look fine, but what am I doing wrong? Thanks for any ideas you guys might have.
Never declare variables in a header file. You can extern the variables, but never declare them. If you declare the variable in the header file, the compiler tries to create the variable each time it reads the header file.
Here’s an example of what you should do:
foo.c:
int myvar;
void foo(void)
{
myvar = 2;
}
bar.c:
extern int myvar;
void bar(void)
{
printf("myvar %d\r", myvar);
}
Alternatively you could get rid of the ‘extern int myvar’; from bar.c and move it to a header file that you include in any c file that uses myvar.
foo.c:
#include "globals.h"
int myvar;
void foo(void)
{
myvar = 2;
}
bar.c:
#include "globals.h"
void bar(void)
{
printf("myvar %d\r", myvar);
}
globals.h:
extern int myvar;
That’s exactly backwards. You should put the extern declaration in the .h file, and actually define the variable in only one .c file.
That’s what I was looking for. Everything compiled just fine. Thanks a bunch!
Alternatively, you could use pointers. Declare variables in main.c, declare pointers to them, and pass said pointers to the ProcessDatefrommasterUP and processdatafrommasterIO functions. Then pass them from there to whatever other functions you want to have access to those vars.