Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I define string constants in C++? [duplicate]

Possible Duplicate:
C++ static constant string (class member)
static const C++ class member initialized gives a duplicate symbol error when linking

My experience with C++ pre-dated the addition of the string class, so I'm starting over in some ways.

I'm defining my header file for my class and want to create a static constant for a url. I'm attempting this by doing as follows:

#include <string>
class MainController{
private:
    static const std::string SOME_URL;
}

const std::string MainController::SOME_URL = "www.google.com";

But this give me a duplicate definition during link.

How can I accomplish this?

like image 859
Thom Avatar asked Sep 27 '11 14:09

Thom


3 Answers

Move the

const std::string MainController::SOME_URL = "www.google.com";

to a cpp file. If you have it in a header, then every .cpp that includes it will have a copy and you will get the duplicate symbol error during the link.

like image 168
David Nehme Avatar answered Nov 17 '22 13:11

David Nehme


You need to put the line

const std::string MainController::SOME_URL = "www.google.com";

in the cpp file, not the header, because of the one-definition rule. And the fact that you cannot directly initialize it in the class is because std::string is not an integral type (like int).

Alternatively, depending on your use case, you might consider not making a static member but using an anonymous namespace instead. See this post for pro/cons.

like image 12
JRL Avatar answered Nov 17 '22 11:11

JRL


Define the class in the header file:

//file.h
class MainController{
private:
    static const std::string SOME_URL;
}

And then, in source file:

//file.cpp
 #include "file.h"

const std::string MainController::SOME_URL = "www.google.com";
like image 4
Nawaz Avatar answered Nov 17 '22 13:11

Nawaz