随笔 - 10  文章 - 0  评论 - 0  阅读 - 2116

编译库文件随笔记录

// mylib.h
#ifndef _MYLIB_H_
#define _MYLIB_H_

#include <stdio.h>

void print();#endif // _MYLIB_H_

 

// mylib.c
#include "mylib.h"

void print() {
    printf("this is a line text\n");
}

 

静态库文件编译:

gcc -c -o mylib.o mylib.c
ar rcs libstatic.a mylib.o

 

静态库测试代码:

// test.c
#include "mylib.h"
#include <dlfcn.h>

int main() {
    print();
}

 

静态库链接:

gcc -o test test.c -L. -lstatic

 

运行:

 

动态库测试代码:

复制代码
// test.c
#include "mylib.h"
#include <dlfcn.h>

int main() {
    const char* error;
    void* handle = dlopen("./libshared.so", RTLD_LAZY);
    error = dlerror();
    if (error) {
        printf("%s\n", error);
        return -1;
    }
    void (*p)() = (void (*)())dlsym(handle, "print");
    error = dlerror();
    if (error) {
        printf("\n");
        printf("%s\n", error);
        return -1;
    }
    p();
    dlclose(handle);

}
复制代码

 

生成动态库文件:

gcc -fPIC -shared -o libshared.so mylib.c

 

编译测试:

gcc -o test test.c -ldl

其中-ldl为dlopen、dlsym等调用库函数的库。

 

运行:

 

posted on   TN-mo  阅读(11)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示