Skip to content

C语言静态库与动态库 #22

@taoeer

Description

@taoeer

1. 文件准备

// hello.c
#include <stdio.h>

void hello(const char *name)
{
  printf("Hello %s\n", name);
}
// hello.h
#ifndef HELLO_H
#define HELLO_H
void hello(const char *name);
#endif
// main.c
#include "hello.h"

int main()
{
  hello("taoeer");
  return 0;
}

2. 编译静态库

1. 生成 .o 目标文件

gcc -c hello.c

2. 生成静态库

ar -crv libhello.a hello.o

-c 是创建库

-r 是将方法添加到库中

-v 显示过程

3. 生成可执行文件

gcc -o main main.c -L. -lhello

-o 指定生成的文件名

-L 指定库文件目录

-l 指定要连接的库名称(不需要前面的‘lib’和扩展名‘.a’)

3. 生成动态库

1. 生成 .o 目标文件

gcc -c hello.c

2. 生成动态库文件

gcc -shared -fPIC -o libhello.so hello.o

-fPIC:代码位置无关

3. 使用库文件

# 编译
gcc -o main main.c -L. -lhello
# 执行
./main

-o 指定生成的文件名

-L 指定库文件目录

-l 指定要连接的库名称(不需要前面的‘lib’和扩展名‘.a’)

执行会报错:
./main: error while loading shared libraries: libhello.so: cannot open shared object file: No such file or directory

原因是系统加载共享库时,找不到对应的共享库文件”libhello.so”, 但是该库确实在当前目录下存在。这是为什么呢?

因为系统默认只会去存储库的标准位置(/lib 或/usr/lib 等)加载,而不会在当前位置寻找。所以将库拷贝到/usr/lib 下,再执行程序,就可以成功。

如果库不在标准位置下,也可以通过设置环境变量”LD_LIBRARY_PATH”来指定加载库的路径。

可以通过 ldd 命令查看可执行程序使用了哪些共享库

image

4. gcc头文件搜索路径

使用如下命令可查看gcc应用层编程的默认头文件搜索路径:

1.For C:

gcc -xc -E -v -

image

2.For C++:

gcc -xc++ -E -v -

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions