Linux中动态加载两个同名so(dlopen动态链接库)

// 当前路径下  ./test1.c

int Func1(int a, int b)
{
    return a+b;
}
 

//编译生成so

gcc -fPIC -shared -o libTest.so test1.c

// 当前路径的test2文件夹中   ./test2/test2.c

int Func1(int a, int b)
{
    return a-b;
}

//编译生成同名so

gcc -fPIC -shared -o libTest.so test2.c

// 当前路径下  ./main.c

#include
#include

typedef int (*pfunc1)(int,int);

void main()
{
    void* handle = dlopen("./libTest.so",RTLD_LAZY);

    pfunc1 f1 = (pfunc1)dlsym(handle,"Func1");

    int c = f1(5,3);

    printf("reslut: %d\n",c);


    void* handle2 = dlopen("./test2/libTest.so",RTLD_LAZY);

    pfunc1 f2 = (pfunc1)dlsym(handle2,"Func1");

    int c2 = f2(5,3);

    printf("reslut: %d\n",c2);
}
 

//编译生成main

gcc -o main main.c -ldl

//运行main

./main

//运行结果

result: 8

result: 2

//结论

Linux中使用alopen可以加载同名so,so中可以包含同名函数。

效果与Windows的loadlibrary一致。

你可能感兴趣的:(Linux,Ubuntu,Kylin,linux)