Static string literal table?

nonot1 picture nonot1 · Jan 8, 2013 · Viewed 15k times · Source

What is the correct way in C++ to create a global & static table of strings?

By "global", I mean: Useable from any file that includes the header. But not part of some run-time created singelton objcet.

By "static", I mean: As little run time set up possable. Data in read only memory pages. Only 1 instance of data per app.

By "string", I mean: Null terminated array of chars is fine. std::string would be nice, but I don't think it can be done in terms of the above. Correct?

By "table", I mean: I mean an indexable array. So I guess not a table per-se. But I'm flexable on this point. Open to ideas.

By "C++", I mean: C++ not C. (Update: C++98, not C++11)

Answer

Jonathon Reinhart picture Jonathon Reinhart · Jan 8, 2013

strings.h

extern const char* table[];

strings.cpp

const char* table[] = {
    "Stack",
    "Overflow",
}

Another take on this, using error codes for a lookup table:

err.h

#define ERR_NOT_FOUND    0x1004
#define ERR_INVALID      0x1005

bool get_err_msg(int code, const char* &msg);

err.cpp

typedef struct {
    int errcode;
    const char* msg;
} errmsg_t;

static errmsg_t errmsg_table[] = {
    {ERR_NOT_FOUND, "Not found"},
    {ERR_INVALID,   "Invalid"}
};

#define ERRMSG_TABLE_LEN  sizeof(errmsg_table)/sizeof(errmsg_table[0])

bool get_err_msg(int code, const char* &msg){
    msg = NULL;
    for (int i=0; i<ERRMSG_TABLE_LEN; i++) {
        if (errmsg_table[i].errcode == code) {
            msg = errmsg_table[i].msg;
            return true;
        }
    }
    return false;
}

main.cpp

#include <stdio.h>
#include "err.h"

int main(int argc, char** argv) {
    const char* msg;
    int code = ERR_INVALID;
    if (get_err_msg(code, msg)) {
        printf("%d: %s\n", code, msg);
    }
    return 0;
}

I'm sure there is a more C++ way of doing this, but I'm really a C programmer.