Associating a Multiple Definition Compilation Error Problem

I have the following "constants" header:

/* constants.h */ #ifdef __cplusplus extern "C" { #endif #pragma once #ifndef CONSTANTS_H #define CONSTANTS_H const char * kFoo = "foo"; const char * kBar = "bar"; #endif #ifdef __cplusplus } #endif 

I #include title of this header in the Xc and Yc files.

Please note that I am not including this in Xh or Yh .

Xc and Yc files are collected in object files, which are stored in a static library called libXY.a .

When I include Xh and Yh in Zh , and when I refer to libXY.a , I cannot compile Zc without errors:

 /* Zh */ #include "Xh" #include "Yh" 

I get the following compilation errors when trying to compile Zc :

 /path/to/libXY.a(Xo):(.data+0x0): multiple definition of `kFoo` /path/to/libXY.a(Yo):(.data+0x0): first defined here /path/to/libXY.a(Xo):(.data+0x8): multiple definition of `kBar` /path/to/libXY.a(Yo):(.data+0x8): first defined here 

I tried installing kFoo and kBar on extern , but that does not help.

How to resolve multiple definitions when I only include constants once (via the #ifndef CONSTANTS_H header protector)?

+6
source share
2 answers

How to resolve multiple definitions when I only include constants once (via the #ifndef CONSTANTS_H header protector)?

With this in constants.h :

 const char * kFoo = "foo"; 

a definition for kFoo will be emitted in every translation that #include constants.h . Thus, a few definitions that then lead to link errors.

As asaelr (+1) remarked, you would solve it like this:

constants.h

 extern const char* const kFoo; 

constants.c

 const char* const kFoo = "foo"; 

(note that I also made a const pointer, which is usually what you want to do in this case)

+9
source

You must not define variables in the header file. define them in one of the source files and declare them ( extern ) in the header file.

(You wrote, β€œI tried configuring kFoo and kBar for extern, but that doesn’t help.” I assume that you did not define them in the source file)

+4
source

Source: https://habr.com/ru/post/907131/


All Articles