tags:

views:

197

answers:

4

Hi, anyone knows why this does not work when I try to include a library with the following declarations:

namespace wincabase
{
  const char* SOMESTRING = "xx";
}

While this is perfectly fine:

namespace wincabase
{
  const int X = 30;
}

I get a "multiple definitions" error with gcc for the first case when I link the lib. Thanks!

+6  A: 

const char* means pointer to const char. This means the pointer itself is not constant.

Hence it's a normal variable, so you'd need to use

extern const char* SOMESTRING;

in the header file, and

const char* SOMESTRING = "xx";

in one compilation unit of the library.


Alternatively, if it's meant to be a const pointer to a const char, then you should use:

const char* const SOMESTRING = "xx";
Tobi
+2  A: 

You're declaring the pointer as const, and then pointing it to a string literal defined in the compilation unit, so you'd be duplicating the string literal if you used this in a header file. What you need to do is declare pointer in the header file, and define the string in a source file in the library.

Header:

extern const char* SOMESTRING;

In some source file in the library:

const char* SOMESTRING = "xx";
Nik
+1  A: 

You need to declare and define them seprately:

Plop.h
======
namespace wincabase
{
   extern const char* SOMESTRING;  // declare
}

Plop.cpp
========
const char* wincabase::SOMESTRING = "xx"; // define
Martin York
+2  A: 

Besides the approach Tobi pointed out:

const char* const SOMESTRING = "xx";

another alternative is to declare it as a const character array:

const char SOMESTRING[] = "xx";

This approach potentially provides the compiler with additional optimization opportunities, such as placing the string in the read-only section of the resulting binary; although it's conceivable the compiler may be able to perform similar optimizations with the first approach.

Void