Language/C&C++
[C/C++] __attribute__((constructor)) and variable initialization in C++.
yhcting
2024. 1. 23. 22:41
Let me share quite interesting observation.
Environment
- clang++:
aarch64-linux-android34-clang++
of android NDK. - Run on android device
Think about following project
a.cpp
namespace {
std::map<std::string, int> m0_;
}
static std::map<std::string, int> m1_;
void noticeFromConstructor(const char *name, int value) {
static std::map<std::string, int> m2_;
m0_[name] = value; // (*1)
m1_[name] = value; // (*2)
m2_[name] = value; // (*3)
}
b.cpp
namespace {
__attribute__((constructor)) void notify() {
noticeFromConstructor("b", 1);
}
c.cpp
__attribute__((constructor)) static void notify() {
noticeFromConstructor("c", 2);
}
SIGSEGV is signalled at both (1) and (2) when it run - from both b.cpp
and c.cpp
- but, (*3) is ok. I think it's because m0_
and m1_
are not initialized yet, but m2_
is initialized.
I'm not sure that there is any explicit description regarding initialization order for this case.