Are you able to set constructor priority across modules in C?

Viewed 58

Are you able to set constructor priority across modules in C?

For example, say I have the following three files:

(1) hw.c:

#include <stdio.h>

int main(void)
{
  fprintf(stdout, "main\n");
}

(2) libhw.c

#include <stdio.h>

__attribute__((constructor(104)))
void my_constructor4(void)
{
  fprintf(stdout, "my_constructor4\n");
}

(3) libprio.c

#include <stdio.h>

__attribute__((constructor(101)))
void my_constructor1(void)
{
  fprintf(stdout, "my_constructor1\n");
}

__attribute__((constructor(102)))
void my_constructor2(void)
{
  fprintf(stdout, "my_constructor2\n");
}

__attribute__((constructor(103)))
void my_constructor3(void)
{
  fprintf(stdout, "my_constructor3\n");
}

And then I compile things with:

gcc -O0 -Wall -g -shared -fPIC libhw.c  -o libhw.so
gcc -O0 -Wall -g -shared -fPIC libprio.c  -o libprio.so
gcc -O0 -Wall -g hw.c -o hw -L. -lprio -lhw

If I run LD_LIBRARY_PATH=. ./hw the output is:

my_constructor4
my_constructor1
my_constructor2
my_constructor3
main

I would like to see the following output:

my_constructor1
my_constructor2
my_constructor3
my_constructor4
main

Thus, I am wondering if the constructors can be run in order of priority even if they are in different modules/libraries regardless of the order they are passed to the linker.

1 Answers

The order of the constructors seems tied to the order in which the libraries are loaded, which in turn seems to be dependent on the linking order when the executable is created. If you switch the linking order you should get the desired constructor order.

gcc -O0 -Wall -g hw.c -o hw -L. -lhw -lprio
Related