You can assign a priority number to objects and files within a single library, and the objects will be initialized at run time according to the order of priority. However, because of the differences in the way modules are loaded and objects initialized on the different platforms, the levels at which you can assign priorities vary among the different platforms, as follows:
On AIX® only, you can additionally set the priority of an entire shared library, by using the priority suboption of the -qmkshrobj compiler option. As loading and initialization on AIX occur as separate processes, priority numbers assigned to files (or to objects within files) are entirely independent of priority numbers assigned to libraries, and do not need to follow any sequence.
Priority numbers can range from -2147483648 to 2147483647. However, numbers from -2147483648 to -2147482625 are reserved for system use. The smallest priority number that you can specify, -2147482624, is initialized first. The largest priority number, 2147483647, is initialized last. If you do not specify a priority level, the default priority is 0 (zero).
The examples below show how to specify the priority of objects within a single file, and across two files. Order of object initialization across libraries provides detailed information on the order of initialization of objects.
The following example shows how to specify the priority for several objects within a source file.
...
#pragma priority(2000) //Following objects constructed with priority 2000
...
static Base a ;
House b ;
...
#pragma priority(3000) //Following objects constructed with priority 3000
...
Barn c ;
...
#pragma priority(2500) // Error - priority number must be larger
// than preceding number (3000)
...
#pragma priority(4000) //Following objects constructed with priority 4000
...
Garage d ;
...
The following example describes the initialization order for objects in two files, farm.C and zoo.C. Both files are contained in the same shared module, and use the -qpriority compiler option and #pragma priority directives.
| farm.C -qpriority=1000 | zoo.C -qpriority=2000 |
|---|---|
... Dog a ; Dog b ; ... #pragma priority(6000) ... Cat c ; Cow d ; ... #pragma priority(7000) Mouse e ; ... |
... Bear m ; ... #pragma priority(5000) ... Zebra n ; Snake s ; ... #pragma priority(8000) Frog f ; ... |
At runtime, the objects in these files are initialized in the following order:
| Sequence | Object | Priority value | Comment |
|---|---|---|---|
| 1 | Dog a | 1000 | Takes option priority (1000). |
| 2 | Dog b | 1000 | Follows with the same priority. |
| 3 | Bear m | 2000 | Takes option priority (2000). |
| 4 | Zebra n | 5000 | Takes pragma priority (5000). |
| 5 | Snake s | 5000 | Follows with same priority. |
| 6 | Cat c | 6000 | Next priority number. |
| 7 | Cow d | 6000 | Follows with same priority. |
| 8 | Mouse e | 7000 | Next priority number. |
| 9 | Frog f | 8000 | Next priority number (initialized last). |