Linking issue with “multiple definition of” compilation error

大城市里の小女人 提交于 2019-12-05 07:20:44

How would I resolve multiple definitions, when I am only including the constants once (via the header guard #ifndef CONSTANTS_H)?

With this in constants.h:

const char * kFoo = "foo";

a definition for kFoo will be emitted in every translation that #includes constants.h. Thus, multiple definitions, which then result in link errors.

As asaelr noted (+1), 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 the pointer const, which is usually what you want to do in this case)

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

(You wrote "I have tried setting kFoo and kBar to extern, but that does not help." I guess that you didn't define them in a source file)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!