Strangely there's almost no online documentation on this subject. I have an application with hard coded strings for the UI and various other things scattered through the source. I'm attempting to round up at least some of them because a number of them need to change depending on what platform the application is compiled for.
I used the second example here (copied below for reference) but it's somewhat light on the details of how this should actually work. It appears that everything is reinitialized in project_strings.cpp and the code is never actually called.
// in your project_strings.h
namespace MyProjectStrings {
const char *password;
...
}
// the project_strings.cpp for the strings
#include "project_strings.h"
namespace MyProjectStrings {
const char *password = "Password:";
...
}
// some random user who needs that string
#include "project_strings.h"
std::string password(MyProjectStrings::password);
Can someone explain this or tell me its a terrible idea and I should do something else?
The example you link is simply declaring some
const char*s in a namespace in a header file and then defining them in a .cpp file. The syntax used is incorrect for C++ though - the declarations in the header file should beextern const char*rather thanconst char*asconstvalues default to internal linkage in C++.Most C++ compiler/linker toolchains will place all the strings from the one translation unit (
project_strings.cpp) together in a read only data segment of the resulting executable.This is a reasonable, simple approach to handling static strings although you probably want something a bit more dynamic / sophisticated if you need to handle localization or other complexities.