Issue
I have static library file(lib_XXX.a
) with global variable defined in it. I am trying to access the global variable in my executable(exe_XXX.o
).
Linker error is coming. Any help would be thankful.
Languae : c
OS : Ubuntu gcc compiler
Sample as follows
exe_xxx.o
module has 2 files resource.h
and main.c
resource.h
code as follows :
#ifndef RESOURCE_H
#define RESOURCE_H
#define APL
extern const StructTest g_AplObjDef;
const StructTest g_AplObjDef = {
abc, def, ghi,
....
};
#endif //APL
main.c
code as follows:
#include "resource.h"
....
....
....
lib_xxx.a
has another main.c
in it. Its sample code as follows:
#include "resource.h"
int main()
{
#if defined(APL)
fun1(g_AplObjDef);
#endif
}
I suspect the reason is because resource.h
included in both the main.c
files.
I couldn't way to get rid of this. Can anyone help ?
Error details: /lib_XXX.a(lib_XXX_a-main.o):(.data.rel.ro.local+0x40): `g_AplObjDef' が重複して定義されています /exe_xxx-main.o:(.data.rel.ro.local+0x260): ここで最初に定義されています
Above error is in Japanese.. 1st line says "Duplicate is defined". 2nd line says "Here it is defined"
Solution
This part:
const StructTest g_AplObjDef = {
abc, def, ghi,
....
};
is a definition, and should not be in a header. Move it to
a .c
file.
The reason for this is that header files are textually inserted, so if a header has a definition, and is included from multiple translation units, the symbol will be defined multiple times, which is an error.
Answered By - sp2danny