gcc __attribute__((constructor)) 运行 与同一翻译单元中的全局变量相关的顺序是什么?
What order does gcc __attribute__((constructor)) run in relation to global variables in same translation unit?
我看到 this question 回答了其中的一些问题,但至少我的问题不是很清楚。
我怀疑我可能不应该访问任何需要代码执行的全局变量(例如 std::string
),但是 POD 变量呢?
std::string s = "hello";
const char* c = "world";
extern std::string s2; // (actually below in the same TU)
__attribute__((constructor)) void init()
{
// safe to assume that !strcmp(c, "world");
// not safe to assume s == "hello"?
// even less safe to assume s2 == "foo";
}
std::string s2 = "foo";
However, at present, the order in which constructors for C++ objects with static storage duration and functions decorated with attribute constructor are invoked is unspecified.
!strcmp(c, "world")
可能是安全的假设。
char* c = "world";
这是错误的格式,因为字符串文字不会隐式转换为指向非常量字符的指针(C++11 起)。
我看到 this question 回答了其中的一些问题,但至少我的问题不是很清楚。
我怀疑我可能不应该访问任何需要代码执行的全局变量(例如 std::string
),但是 POD 变量呢?
std::string s = "hello";
const char* c = "world";
extern std::string s2; // (actually below in the same TU)
__attribute__((constructor)) void init()
{
// safe to assume that !strcmp(c, "world");
// not safe to assume s == "hello"?
// even less safe to assume s2 == "foo";
}
std::string s2 = "foo";
However, at present, the order in which constructors for C++ objects with static storage duration and functions decorated with attribute constructor are invoked is unspecified.
!strcmp(c, "world")
可能是安全的假设。
char* c = "world";
这是错误的格式,因为字符串文字不会隐式转换为指向非常量字符的指针(C++11 起)。