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

来源:互联网 发布:餐厅收银软件 免费 编辑:程序博客网 时间:2024/06/07 03:25

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:cleanlibmath:libmath.o    ar rcs $@ $^libmath.o:libmath.c libmath.hclean:    rm libmath.a libmath.olibmath.c:

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

原创粉丝点击