4. 共享库的构建与安装
任务说明
本案例目标:使用 Autotools 构建一个共享库(libhello.so),并将其安装到系统目录,同时生成可供外部程序链接的头文件与 pkg-config 元数据。最终验证:外部程序能够通过 pkg-config 获取编译参数并成功链接运行。
项目结构
shared-lib-demo/
├── configure.ac
├── Makefile.am
├── src/
│ ├── Makefile.am
│ ├── hello.h
│ └── hello.c
└── test/
├── Makefile.am
└── main.c
实现代码
configure.ac
AC_INIT([shared-lib-demo], [1.0])
AM_INIT_AUTOMAKE([foreign])
LT_INIT
AC_PROG_CC
AC_CONFIG_HEADERS([config.h])
AC_CONFIG_FILES([Makefile
src/Makefile
test/Makefile])
AC_OUTPUT
顶层 Makefile.am
SUBDIRS = src test
pkgconfigdir = $(libdir)/pkgconfig
pkgconfig_DATA = libhello.pc
libhello.pc(置于顶层目录)
prefix=@prefix@
exec_prefix=@exec_prefix@
libdir=@libdir@
includedir=@includedir@
Name: libhello
Description: Simple shared library demo
Version: 1.0
Libs: -L${libdir} -lhello
Cflags: -I${includedir}
src/Makefile.am
lib_LTLIBRARIES = libhello.la
libhello_la_SOURCES = hello.c
include_HEADERS = hello.h
libhello_la_LDFLAGS = -version-info 1:0:0
src/hello.h
#ifndef HELLO_H
#define HELLO_H
int hello_greet(const char *name);
#endif
src/hello.c
#include <stdio.h>
#include "hello.h"
int hello_greet(const char *name) {
return printf("Hello, %s!\n", name);
}
test/Makefile.am
bin_PROGRAMS = demo
demo_SOURCES = main.c
demo_LDADD = $(top_builddir)/src/libhello.la
test/main.c
#include <hello.h>
int main(void) {
return hello_greet("Autotools") < 0 ? 1 : 0;
}
构建与安装
autoreconf -ivf
./configure --prefix=/usr/local
make
sudo make install
sudo ldconfig
验证方法
安装完成后,在任意目录执行以下命令验证共享库可用性:
pkg-config --cflags --libs libhello
# 预期输出: -I/usr/local/include -L/usr/local/lib -lhello
echo '#include <hello.h>
int main(){return hello_greet("pkg-config")<0;}
' > /tmp/verify.c
cc /tmp/verify.c -o /tmp/verify $(pkg-config --cflags --libs libhello)
/tmp/verify
# 预期输出: Hello, pkg-config!
判定标准:pkg-config 能正确输出编译参数;外部编译链接成功且运行打印 Hello, pkg-config!,退出码为 0。同时确认 /usr/local/lib/libhello.so 存在且 ldconfig -p | grep libhello 能检索到该库。
关键说明
本案例使用 Libtool 管理共享库版本信息(-version-info 1:0:0),生成 .so 符号链接及 .la 元数据文件。include_HEADERS 自动将头文件安装至 $(includedir),pkgconfig_DATA 将 .pc 文件安装至 pkg-config 搜索路径。测试程序通过 $(top_builddir)/src/libhello.la 链接,确保在构建树内即可运行验证。