xcode生成dylib后缀的动态库并使用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_31177681/article/details/88112123

然后添加dylib的要编译的文件:

编写动态库时使用代码

MacSDK.h

#ifndef MacSDK_h

#define MacSDK_h

#include <stdio.h>

int hello();

int add(int a,int b);

int sub(int a, int b);

#endif /* MacSDK_h */

MacSDK.c

#include "MacSDK.h"

int hello() {

    return 1;

}

int add(int a,int b)

{

    return (a + b);

}

int sub(int a, int b)

{

    return (a - b);

}

程序调用动态库

#include <stdio.h>
#include <dlfcn.h>//dlopen和dlsym需要

#import "MacSDK.h"

typedef int (*CAC_FUNC)(int, int);

int main(int argc, const char * argv[]) {
    // insert code here...

CAC_FUNC cac_func = NULL;

void *handle;

char *error;

handle = dlopen("./SDK/libdylib.dylib", RTLD_LAZY);

if (!handle)  {

printf("failed to dlopen libOeBase.dylib \n");

}

//获取一个函数

*(void **) (&cac_func) = dlsym(handle, "add");

if ((error = dlerror()) != NULL) {

fprintf(stderr, "%s\n", error);

exit(EXIT_FAILURE);

}

printf("add: %d\n", (*cac_func)(2,7));

cac_func = (CAC_FUNC)dlsym(handle, "sub");

printf("sub: %d\n", cac_func(9,2));


    return 0;
}
 

猜你喜欢

转载自blog.csdn.net/sinat_31177681/article/details/88112123