Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Revisiting the array of strings initialization in C

I want to initialize in plain C an array of strings with the following requirements:

(A) I need the strings in a header file, since some other modules are using them as plain strings, so I declared in the header file:

extern const char* const ERRMSG_VM_0001;
extern const char* const ERRMSG_VM_0002;
extern const char* const ERRMSG_VM_0003;
extern const char* const ERRMSG_VM_0004;

and in the source file:

const char* const ERRMSG_VM_0001 = "[VM-001] some text ";
const char* const ERRMSG_VM_0002 = "[VM-002] more text ";
const char* const ERRMSG_VM_0003 = "[VM-003] other text ";
const char* const ERRMSG_VM_0004 = "[VM-003] and even more";

(B) I need these strings also in an array, so I tried in the (same) source (as above):

static const char* error_table[4] =
{
    ERRMSG_VM_0001,
    ERRMSG_VM_0002,
    ERRMSG_VM_0003,
    ERRMSG_VM_0004
};

Obviously, the compiler complains error: initializer element is not constant ... so now I am wondering how can I achieve this in a pure C way, not C++ (this is similar to Tricky array Initialization but it's not the same).

like image 549
Ferenc Deak Avatar asked Mar 04 '26 09:03

Ferenc Deak


2 Answers

Compilers are able to find matching string literals and optimize the binary. (it may be an option)

I'd suggest to declare defines only and create a const

#define ERRMSG_VM_0001 "[VM-001] some text "
...

and

static const char* error_table[4] =
{
    ERRMSG_VM_0001,
    ERRMSG_VM_0002,
    ERRMSG_VM_0003,
    ERRMSG_VM_0004
};

would be now OK. and the resulting binary code will be the one you want.

like image 134
V-X Avatar answered Mar 05 '26 21:03

V-X


static const char* error_table[4] =
{
    "[VM-001] some text ",
    "[VM-002] some text ",
    "[VM-003] some text ",
    "[VM-004] some text ",
};

then

ERRMSG_VM_0001 = error_table[0];
like image 45
Keith Nicholas Avatar answered Mar 05 '26 22:03

Keith Nicholas