Reputation: 300
I have two *.c
files. fileA.c
and fileB.c
I'm defining a structure with the same name in both files but both of them are locally in each file as global variables.
For example:
fileA.c
typedef struct
{
int a;
}MyHandler_t;
MyHandler_t myHandler =
{
.a = 0,
};
fileB.c
typedef struct
{
int a;
}MyHandler_t;
MyHandler_t myHandler;
The problem is that if I try to initialize the variable a in the structure in file B i get multiple definition of "myHandler"
.
Even if I try to leave it with empty brackets I get the same error.
Why is that happening?
Both files contain functions that are used in the main.c in the main function but these structures above are local global variables that used for state machine control.
Upvotes: 2
Views: 511
Reputation: 67476
Move the typedef
to the .h
header file. In both of the .C Giles include the header file. In one of the C files make the variable extern
and remove the initialization. You can fave only one initialization of the same variable in the whole project
Yuo can also meke both static and they will be global in the compilation unit scope (ie file)
Upvotes: 0
Reputation: 171127
There is no such thing as a "local global variable" in C. myHandler
is a global variable, defined in both source files. That is invalid, since each global variable can only have one definition.
If you want each source file to have its own file-local myHandler
variable, you must declare it static
:
static MyHandler_t myHandler =
{
.a = 0,
};
Note that this way, code in other source files cannot access that variable by name.
Upvotes: 3