Linux的Terminal中如何生成静态库以及如何使用静态库

Linux的Terminal中如何生成静态库以及如何使用静态库

生成静态库文件分为两个步骤
hello.c

#include<stdio.h>
void hello()
{
printf("hello\n");
}

main.c

#include<stdio.h>
#include"hello.h"
int main()
{
printf("Hello main\n");
hello();
return 0;
}
  1. 生成目标文件—hello.o
    root@ubuntu:~/lesson/chap2/2-6/tmp# gcc -o hello.o -c hello.c
    root@ubuntu:~/lesson/chap2/2-6/tmp# ls
    hello.c hello.h hello.o main.c makefile

    只编译不链接.
  2. 链接为静态库文件
    root@ubuntu:~/lesson/chap2/2-6/tmp# ar rcs libhello.a hello.o
    root@ubuntu:~/lesson/chap2/2-6/tmp# ls
    hello.c hello.h hello.o libhello.a main.c makefile

    其中,生成的静态库libhello.a中的前缀为lib 后缀为.a 文件名为hello.

使用库
用gcc生成可执行文件(编译main.c)
root@ubuntu:~/lesson/chap2/2-6/tmp# gcc -o test main.c -L./ -lhello
root@ubuntu:~/lesson/chap2/2-6/tmp# ls
hello.c hello.h hello.o libhello.a main.c makefile test
root@ubuntu:~/lesson/chap2/2-6/tmp# ./test
Hello main
hello

其中,指定库路径(./当前路径)为:-L库路径 指定库文件为(libhello.a): `-l库名称““
gcc -o test main.c -L./ -lhello


**makefile 生成静态库,并且使用静态库.**


makefile:


.PHONY:clean
libmath:libmath.o
    ar rcs $@ $^
libmath.o:libmath.c libmath.h
clean:
    rm libmath.a libmath.o

libmath.c:

void libmath_init()
{
printf(“libmath_init …\n”);
}“`

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
在VSCode添加.a静态库,你需要进行以下步骤: 1. 首先,在你的项目文件夹下创建一个名为"lib"的文件夹,用于存放你的静态库文件。 2. 将你的.a静态库文件复制到这个"lib"文件夹。 3. 在你的项目文件夹下创建一个名为".vscode"的隐藏文件夹(如果已存在则跳过此步骤)。 4. 在".vscode"文件夹创建一个名为"c_cpp_properties.json"的文件。 5. 在"c_cpp_properties.json"文件添加以下配置: ```json { "configurations": [ { "name": "Linux", "includePath": [ "${workspaceFolder}/**", "/usr/local/include", "/usr/include" ], "defines": [], "compilerPath": "/usr/bin/gcc", "cStandard": "c11", "cppStandard": "c++17", "intelliSenseMode": "gcc-x64", "browse": { "path": [ "${workspaceFolder}/**", "/usr/local/include", "/usr/include" ], "limitSymbolsToIncludedHeaders": true, "databaseFilename": "" } } ], "version": 4 } ``` 6. 保存并关闭"c_cpp_properties.json"文件。 7. 接下来,在你的项目文件夹下打开终端(Terminal)。 8. 在终端输入以下命令来编辑你的项目的"CMakeLists.txt"文件: ``` code CMakeLists.txt ``` 9. 在"CMakeLists.txt"文件的末尾添加以下代码,用于链接你的.a静态库: ``` target_link_libraries(${COMPONENT_LIB} INTERFACE "${CMAKE_CURRENT_LIST_DIR}/lib/your_library.a") ``` 注意将"your_library.a"替换为你实际的.a静态库文件名。 10. 保存并关闭"CMakeLists.txt"文件。 11. 最后,在VSCode的侧边栏选择"终端"(Terminal)选项卡,点击"运行生成任务"(Build)来重新构建你的项目。 12. 构建成功后,你就可以在你的项目使用该.a静态库了。 请确保在以上步骤正确替换和修改相关文件和路径,以适应你的项目需求。<span class="em">1</span><span class="em">2</span><span class="em">3</span><span class="em">4</span>

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Gkbytes

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值