发新帖

mac动态链接库的生成和使用

零下一度 2022-2-26 1241

源文件

动态库的头文件

//
// Created by binny on 2019/9/24.
//
#ifndef NDK_TEST_H
#define NDK_TEST_H
void sayHello();
#endif //NDK_TEST_H


动态库的源文件

test.c

//
// Created by binny on 2019/9/24.
//
#include "test.h"
#include "stdio.h"
void sayHello() {
    printf("JNI--test");
}

test2.c

//
// Created by binny on 2019/9/24.
//
#include "test.h"
#include "stdio.h"
void sayHello(){
    printf("JNI--test---2");
}

主函数源文件

//
// Created by binny on 2019/9/24.
//
#include "test.h"
int main() {
    sayHello();
    return 0;
}


动态库

动态库名字为libtest.dylib

注意动态库的名字必须为 libxxxx.dylib

不同操作系统的动态链接库后缀不相同

Windows里动态链接库后缀为 .dll(Dynamic Link Library)

Linux里后缀为 .so

Mac里后缀为 .dylib

生成 test 动态库

-o 链接

-c 将.c源文件编译成.o目标文件,不进行链接


编译

clang -c test.c

创建动态链接库:

生成动态库:

clang -shared test.o -o test.dylib

使用动态链接库

-l(小写L)后接xxxx 表示调用libxxxx.dylib 库

如果库不在系统默认的目录下要使用-L后接路径 再接-lxxxxx

-I(大写i)后接路径,表示在此路径下寻找头文件 xxxx.h

编译 mian函数所在的源文件

clang main.c -c

链接

clang main.o -L. -l test -o main

-L. 意思是在当前目录下(./)寻找库

执行

./main

输出结果:JNI--test%


生成 test2 动态库

使用test2.c作为动态库源文件

编译:

clang -c test2.c

生成动态库:

clang -shared test2.o libtest.dylib

执行mian文件,输出JNI--test222%


注意事项

动态库的名字文字必须为:libxxxx.dylib



作者:枫叶海棠

链接:https://www.jianshu.com/p/246e015f00d1

来源:简书


最新回复 (0)
返回
零下一度
主题数
931
帖子数
0
注册排名
1