MIKU_LINK
MIKU_LINK

Reputation: 192

The char* constant value ERROR with GNU G++ compiler

I write sevaral files with the relationship like:

file A.h:

#ifndef MACRO_HEADER
#define MACRO_HEADER
const char* CONST_CHAR_NAME = "name";
#endif

file B.h(B.cpp) and file C.h(C.cpp) also include this common type definition header A.h. When the g++ finally combines the obj files to lib, it gives out he redefinition error.I confess that I make a mistake and I should define the constant as:

const char* const CONST_CHAR_NAME = "name"; //This is OK 

But why compiler gives me a redefinition ERROR? Is const char* not a constant value?But I use typeid.name to check the types of const char * and cosnt char* const. They are the same:char const * . I am confused with the ERROR.

Upvotes: 0

Views: 1324

Answers (3)

Some programmer dude
Some programmer dude

Reputation: 409404

It gives errors because CONST_CHAR_NAME is defined in multiple "translation units" (a translation unit is basically a single source file and all included header files). You have to declare it extern then in one source file define the constant.

So in the header file:

extern const char* CONST_CHAR_NAME;

And in one source file:

const char* CONST_CHAR_NAME = "name";

Edit: Difference between const char* and const char* const

The declaration

const char* CONST_CHAR_NAME;

creates a pointer to a constant string. You can assign to it, as long as it points to a constant string. I.e. both lines below are okay:

CONST_CHAR_NAME = "foo";
CONST_CHAR_NAME = "bar";

On the other hand you have

const char* const CONST_CHAR_NAME;

The above create a constant pointer to a constant string. This means you can not assign to the pointer again, so the two assignments above are not okay.

Upvotes: 1

Mark Ransom
Mark Ransom

Reputation: 308462

The problem is that you're defining the same variable name in multiple places, i.e. every source file that includes the .h.

You can eliminate the linker errors by declaring each definition to be local to the source file using the static keyword:

static const char* CONST_CHAR_NAME = "name";

Upvotes: 2

user1610015
user1610015

Reputation: 6678

Actually you should declare it as:

const char CONST_CHAR_NAME[] = "name";

Upvotes: -1

Related Questions