本文介绍了__attribute __((init_priority(X)))的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我在GCC中使用 __ attribute __((init_priority(X))),如下所示: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;。让我们说file1.cpp和file2.cpp。 如果我在同一个库中使用它的工作原理,name1在name2之前初始化,但是如果我在不同的库中使用它,初始化的顺序不是预期的顺序。我读gcc文档,这应该在不同的库中工作,我期望,定义初始化的顺序。在使用这个方式有什么问题吗?你有同样的问题吗?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:重构不是解决这个问题,因为我必须从Visual Studio移植一个非常大的项目。PS: refactoring is not a solution for this problem because I must port a very big project from Visual Studio.推荐答案 gcc文档(gcc 4.4)说:The gcc documentation (gcc 4.4) says:在标准C ++中,保证在命名空间范围中定义的对象被严格按照它们在给定翻译单元中的定义 。对于跨翻译单位的初始化,不保证是。但是,GNU C ++允许用户控制对象初始化的顺序在命名空间范围中使用`init_priority'属性定义指定相对PRIORITY,一个常数整数表达式目前约在101和65535之间。较低的数字表示较高的优先级。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.没有任何迹象表明这适用于图书馆,图书馆。我希望静态库(libxyz.a)在这方面与单个对象文件一样工作,因为它们只是对象文件的集合,文档的措辞表明它在翻译单元(即不同的对象文件)。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).然而,共享库本身就是有效的可执行文件---在给定的共享库中,初始化按照指定的顺序完成,但共享库作为整体以动态加载器指定的顺序初始化,即liba.so根据加载器的排序标准在libb.so之前或之后加载,并且init_priority属性不会影响该顺序。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. 这篇关于__attribute __((init_priority(X)))的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 09-03 05:23