C ++ constant in the library; does not work
does anyone know why this doesn't work when i try to include a library with the following declarations:
namespace wincabase
{
const char* SOMESTRING = "xx";
}
So far this is fine:
namespace wincabase
{
const int X = 30;
}
I am getting a "multiple definitions" error with gcc for the first time I link the lib. Thanks!
a source to share
const char * means pointer to const char. This means that the pointer itself is not .
Hence this is a normal variable, so you will need to use
extern const char* SOMESTRING;
in the header file and
const char* SOMESTRING = "xx";
in one block of library compilation.
Alternatively, if it should be a const pointer to const char, you should use:
const char* const SOMESTRING = "xx";
a source to share
You declare a pointer as const and then point it to a string literal defined in the compilation unit, so you must duplicate the string literal if you used it in the header file. What you need to do is declare the pointer in the header file and define the line in the source file in the library.
Title:
extern const char* SOMESTRING;
In some source file in the library:
const char* SOMESTRING = "xx";
a source to share
Beyond the approach, Toby noted:
const char* const SOMESTRING = "xx";
Another alternative is to declare the character array const :
const char SOMESTRING[] = "xx";
This approach potentially provides the compiler with additional optimization options, such as placing the string in a read-only section of the resulting binary; although it is possible that the compiler can perform similar optimizations using the first approach.
a source to share