Reputation: 6166
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()
{
}
};
Upvotes: 46
Views: 59854
Reputation: 25053
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.
Upvotes: 78
Reputation: 6635
My use-case:
a.hpp
, b.hpp
, and, c.hpp
which contained some utility methods.util.hpp
which acted as an aggregator for the above files.In my case, the extern
did not work but static
worked.
I had to use:
header guards
to avoid errors in Visual Studio code.static
with functions to avoid compile-time errors.Check out this article too.
Upvotes: 0
Reputation: 5947
I also ran into this issue, but for me the solution was different. I had put overloaded operators (==, !=, <<) in my header file and implemented them. This was causing an issue in other files where I also used ==, !=, or <<. To solve this, I moved the implementation into the .cpp file and left the declaration in the header file.
Edit:
This can also be caused if:
.cpp
files instead of .h
files. You can fix this by switching the import to use .h
instead of .cpp
..cpp
file (among other solutions).Upvotes: 13
Reputation: 76531
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";
Upvotes: 12