Search code examples
cstructdefinition

Multiple definition of object file


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.


Solution

  • 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.