Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

duplicate symbol error C++

Tags:

c++

I have added some const character in my file as under. The error i get is duplicate symbol _xyz(say). What is the problem with it and how could i get out of this.

const char* xyz = "xyz"; class Abc { public:     Abc()     {     } }; 
like image 594
boom Avatar asked May 24 '10 05:05

boom


People also ask

What is duplicate symbol error?

Solution. Duplicate symbols occur when you have both added an implementation file (. cpp) to your project and #included it. This way, the implementation file (. cpp) gets compiled twice: once as a module in your project (as it is added to your project) and subsequently as a piece of #included code.

What does 1 duplicate symbol for architecture x86_64 mean?

duplicate symbol _OBJC_IVAR_$_BLoginViewController._hud in: 17 duplicate symbols for architecture x86_64. "Means that you have loaded same functions twice. As the issue disappear after removing -ObjC from Other Linker Flags, this means that this option result that functions loads twice:"


2 Answers

If this is in a header file, you're defining xyz every time you #include it.

You can change the declaration as @R Samuel Klatchko shows. The usual way (if the data isn't const) is like this:

In Abc.h:

extern char *xyz; 

In Abc.cpp:

char *xyz = "xyz"; 

Edited to add

Note that header guards will not solve this problem:

#ifndef XYZ_H #define XYZ_H ... #endif 

Header guards prevent "redefinition" errors, where the same symbol appears twice in the same compilation unit. That's a compiler error.

But even with header guards the definition of xyz will still appear in every source file that includes it, causing a "duplicate symbol" error, which is a linker error.

It would have been more helpful if the original poster had mentioned that, of course.

like image 112
egrunin Avatar answered Sep 22 '22 02:09

egrunin


The problem is every source file that includes your header file gets it's own copy of xyz with external linkage.

The easiest way to fix that is to give xyz internal linkage. You can do that by making the pointer itself const in addition to having the underlying char's const:

const char* const xyz = "xyz"; 
like image 21
R Samuel Klatchko Avatar answered Sep 20 '22 02:09

R Samuel Klatchko