so加载的构造函数和析构函数

http://blog.csdn.net/linuw/article/details/6048307

__attribute__ ((constructor))指定的函数在共享库loading的时候调用,__attribute__ ((destructor))指定的函数在共享库unloading的时候调用。

 

so代码:

#include <stdio.h>

__attribute__ ((constructor)) static void so_init(void);
__attribute__ ((destructor)) static void so_deinit(void);

void so_init(void)
{
    printf("call so init.\n");
}

void so_deinit(void)
{
    printf("call so deinit.\n");
}

void test1()
{
    printf("call test1.\n");
}

void test2()
{
    printf("call test2.\n");
}

void test3()
{
    printf("call test3.\n");
}


/*
gcc -fPIC -c so_lib.c   
gcc -shared -o libxxx.so so_lib.o
*/

 

 

app代码:

#include <stdlib.h>
#include <stdio.h>
#include <dlfcn.h> /* dlopen, dlsym, dlclose */

void test1();
void test2();
void test3();

int main(int argc, char **argv)
{
    test1();
    test2();
    test3();

    /* below only for testing dynamic linking loader */
    void *handle;
    void (*test)();
    char *error;

    handle = dlopen ("./libxxx.so", RTLD_LAZY);
    if (!handle) {
        fputs(dlerror(), stderr);
        exit(1);
    }

    test = dlsym(handle, "test2");
    if ((error = dlerror()) != NULL)  {
        fputs(error, stderr);
        exit(1);
    }

    (*test)();
    dlclose(handle);

    return 0;
}

/*
gcc so_app.c -ldl -L./ -lxxx 
  
export LD_LIBRARY_PATH=./:$LD_LIBRARY_PATH && ./a.out 
*/

 

posted @ 2017-04-10 20:28  soul.stone  阅读(1038)  评论(0编辑  收藏  举报