tags:

views:

82

answers:

4

Hi,

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()
    {
    }
};
+5  A: 

If this is in a header file, you're declaring 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.

egrunin
A: 

Please, provide a meaningful description of the problem. What's "my file"? What "const character" are you taking about?

For what you provided so far I can only guess that you added the above definition of xyz to a header file and then included it into several translation units. The result: object xyz got defined more than once. Hence the error.

AndreyT
+4  A: 

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";
R Samuel Klatchko
+1 It is obviusly the best solution. `const` is always good.
Alexey Malistov
const is definitely good, but this just hides the problem that there is an instance of the same data from every file now.
Mark B
A: 

If you are defining const char* xyz = "xyz"; in a header file make sure you use include guards so that there are not multiple definitions. So if this was in header abc.h you might want to do something like this:

#ifndef ABC_H
#define ABC_H

//rest of header file

#endif

If you are defining: const char* xyz = "xyz"; in a regular file then you will need to use the extern keyword everywhere else to tell the compiler that it is defined elsewhere so it does not try to redefine it.

shuttle87