Skip to content

Some shared object constructors are not called #139

@capehill

Description

@capehill

Problem: only 1 of 2 constructors in shared object are called. Both constructors are called when library is linked statically. (Both destructors are called in all cases). Not sure if this problem is related to GCC or elf.library or something else.

Using GCC 11.2. Here is a small example:

-- lib.c

#include <stdio.h>

void __attribute__((constructor(101))) ctor()
{
    printf("%s\n", __func__);
}

void  __attribute__((destructor(101))) dtor()
{
    printf("%s\n", __func__);
}

void __attribute__((constructor(102))) ctor2()
{
    printf("%s\n", __func__);
}

void  __attribute__((destructor(102))) dtor2()
{
    printf("%s\n", __func__);
}

int function(int x)
{
    printf("%s %d\n", __func__, x);

    return x;
}

-- main.c

#include <stdio.h>

int function(int);

int main()
{
    int result = function(123);

    printf("%s result %d\n", __func__, result);

    return 0;
}

-- makefile

CC=gcc

all:
	$(CC) -o lib.o -c lib.c -fPIC
	$(CC) -o libf.so lib.o -shared
	ar cruv  libf.a lib.o
	ranlib libf.a
	$(CC) -o test_dyn main.c -use-dynld -L. -lf -athread=native
	$(CC) -o test_static main.c -L. -lf -athread=native

-- output

ctor2 call is missing here:

constructor> test_dyn
ctor
function 123
main result 123
dtor2
dtor
constructor> test_static
ctor
ctor2
function 123
main result 123
dtor2
dtor

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions