Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
497 views
in Technique[技术] by (71.8m points)

c++ - __attribute__((init_priority(X))) in GCC

I'm using __attribute__((init_priority(X))) in GCC like this:

Type1 __attribute__ ((init_priority (101))) name1 = value1;
Type2 __attribute__ ((init_priority (102))) name2 = value2;

in different source files. Let's say file1.cpp and file2.cpp. If I use this in same library it works as expected, name1 is initialized before name2 but if I use this in different libraries the order of initialization is not the expected one. I read on gcc documentation that this should work in different libraries as I expect, to define the order of initialization. Is there something wrong in the way I use this? Did you have same problem?

PS: refactoring is not a solution for this problem because I must port a very big project from Visual Studio.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The gcc documentation (gcc 4.4) says:

`init_priority (PRIORITY)'

In Standard C++, objects defined at namespace scope are guaranteed to be initialized in an order in strict accordance with that of their definitions in a given translation unit. No guarantee is made for initializations across translation units. However, GNU C++ allows users to control the order of initialization of objects defined at namespace scope with the `init_priority' attribute by specifying a relative PRIORITY, a constant integral expression currently bounded between 101 and 65535 inclusive. Lower numbers indicate a higher priority.

Nowhere is there any indication of how this applies with respect to libraries, especially shared libraries. I would expect static libraries (libxyz.a) to work the same as individual object files in this respect, since they are just a collection of object files, and the wording of the documentation suggests that it works across translation units (i.e. with different object files).

However, shared libraries are effectively executables in their own right --- within a given shared library the initialization is done in the specified order, but shared libraries are initialized as a whole in the order specified by the dynamic loader i.e. liba.so is loaded either before or after libb.so based on the ordering criteria of the loader, and the init_priority attribute cannot affect that ordering.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...