I have a C++ project with const string
constants in two .o
files, where the constant in one file is initialized using the value in the other file. This used to work fine, but now that I'm using a more recent compiler, I'm getting a seg fault as soon as I launch the program, which I've tracked it to the initialization of the dependent constant.
Minimal equivalent example:
mystruct.h:
#include <string>
struct mystruct {
static const string myconst;
}
mystruct.cc:
#include <mystruct.h>
const string mystruct::myconst = "a"
prog.cc:
#include <mystruct.h>
const string mydependentconst = mystruct::myconst + "b";
int main() {}
This code sometimes segfaults because mystruct::myconst
has not yet been initialized when mydependentconst
gets initialized.
I have fixed my code by making the variable initialization independent (effectively, mydependenconst = "ab"
), but I would like to know: is it actually undefined behaviour and was I just lucky before?
I think this boils down to whether I can expect a specific order of initialization of constants in my .o
files, or if I have to assume the order is unspecified.
Note that I have no problem using mystruct::myconst
inside functions anywhere, I'm only getting this seg fault in this file-global constant initialization in prog.cc
.
Context: this occurs in a 15-year old C++ project (using g++
with -std=gnu++98
) which I'm trying to revive on a newer OS. It works fine on CentOS 6, now I'm fixing it to work on CentOS 7 and next I will do more recent OS's too.