简体   繁体   中英

What order does gcc __attribute__((constructor)) run in relation to global variables in same translation unit?

I saw this question answering some of this, but at least not clearly my question.

I suspect that I should probably not access any global variables that requires code to execute (eg std::string ), but how about POD variables?

std::string s = "hello";
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";

The documentation says:

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") is probably safe to assume.


 char* c = "world";

This is ill-formed because string literal doesn't implicitly convert to a pointer to non-const char (since C++11).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM