Home

2023-07-24

Did you know that shared libraries can have constructors and destructors?

libmy.c
#include <stdio.h>
__attribute__((constructor)) static void init1(void) {
    puts("init1");
}
__attribute__((constructor)) static void init2(void) {
    puts("init2");
}
__attribute__((destructor)) static void term1(void) {
    puts("term1");
}
__attribute__((destructor)) static void term2(void) {
    puts("term2");
}
main.c
#include <dlfcn.h>
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    void *mylib = dlopen("libmy.dylib", RTLD_LAZY);
    if (!mylib) {
        fprintf(stderr, "dlopen: %s\n", dlerror());
        return EXIT_FAILURE;
    }
    if (dlclose(mylib)) {
        fprintf(stderr, "dlclose: %s\n", dlerror());
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}
Results
$ ./main 
init1
init2
term2
term1