说明
本文是个人学习用的非官方中英对照译文,原文:https://diveintosystems.org/book/C2-C_depth/advanced_writing_libraries.html。
原书采用 CC BY-NC-ND 4.0 许可(禁止演绎),请勿公开传播本译文。
标为「译注」「现代更新」的内容是译者补充,不代表原书作者观点;代码与原文逐字一致,未作改动。
2.9.6. Writing and Using Your Own C Libraries
程序员通常把大型 C 程序按相关功能划分成独立的模块(module,即单独的 .c 文件)。多个模块共用的定义放在头文件(.h 文件)中,由需要它们的模块包含。类似地,C 库代码也由一个或多个模块(.c 文件)和一个或多个头文件(.h 文件)实现。C 程序员常常把常用功能实现成自己的 C 库。写成库之后,程序员只需在库中实现一次这些功能,之后编写的任何 C 程序都可以使用它们。
Programmers typically divide large C programs into separate modules (i.e., separate
.cfiles) of related functionality. Definitions shared by more than one module are put in header files (.hfiles) that are included by the modules that need them. Similarly, C library code is also implemented in one or more modules (.cfiles) and one or more header files (.hfiles). C programmers often implement their own C libraries of commonly used functionality. By writing a library, a programmer implements the functionality once, in the library, and then can use this functionality in any subsequent C program that they write.
在使用、编译与链接库一节中,我们介绍了如何在 C 程序中使用、编译和链接 C 库代码。本节讨论如何在 C 中编写和使用自己的库。这里介绍的内容同样适用于组织和编译由多个 C 源文件和头文件构成的大型 C 程序。
In the Using, Compiling, and Linking Libraries section, we describe how to use, compile, and link C library code into C programs. In this section, we discuss how to write and use your own libraries in C. What we present here also applies to structuring and compiling larger C programs composed of multiple C source and header files.
在 C 中创建一个库的步骤是:
To create a library in C:
- 在头文件(
.h)中定义库的接口。任何想使用这个库的程序都必须包含这个头文件。
- Define an interface to the library in a header (
.h) file. This header file must be included by any program that wants to use the library.
- 在一个或多个
.c文件中编写库的实现。这组函数定义实现了库的功能。其中一些函数可能是供库的用户调用的接口函数,另一些可能是库的用户无法调用的内部函数(内部函数是库实现良好模块化设计的一部分)。
- Create an implementation of the library in one or more
.cfiles. This set of function definitions implement the library’s functionality. Some functions may be interface functions that users of the library will call, and others may be internal functions that cannot be called by users of the library (internal functions are part of good modular design of the library’s implementation).
- 编译出库的二进制形式,以便链接到使用该库的程序中。
- Compile a binary form of the library that can be linked into programs that use the library.
库的二进制形式可以在编译使用该库的应用代码时,直接从库的源文件构建出来。这种方法把库文件编译成 .o 文件,并把它们静态链接到二进制可执行文件中。以这种方式引入库,通常适用于你为自己编写的库代码(因为你能拿到它的 .c 源文件),这也是用多个 .c 模块构建可执行文件的方法。
The binary form of a library could be directly built from its source file(s) as part of compiling the application code that uses the library. This method compiles the library files into
.ofiles and statically links them into the binary executable. Including libraries this way often applies to library code that you write for your own use (since you have access to its.csource files), and it’s also the method to build an executable from multiple.cmodules.
另一种做法是,把库编译成二进制归档文件(.a)或共享目标文件(.so),供想使用这个库的程序使用。这种情况下,库的用户往往拿不到库的 C 源代码文件,因而无法把库代码与使用它的应用代码直接一起编译。当程序使用这种预编译的库(例如 .a 或 .so)时,必须用 gcc 的 -l 命令行选项把库代码显式链接到可执行文件中。
Alternatively, a library could be compiled into a binary archive (
.a) or a shared object (.so) file for programs that want to use the library. In these cases, users of the library often will not have access to the library’s C source code files, and thus they are not able to directly compile the library code with application code that uses it. When a program uses such a precompiled library (e.g., a.aor.so), the library’s code must be explicitly linked into the executable file usinggcc‘s-lcommand line option.
我们详细讨论的是程序员能够拿到各个库模块(.c 或 .o 文件)的情形下,如何编写、编译和链接库代码。这些内容同样适用于设计和编译划分为多个 .c 和 .h 文件的大型 C 程序。对于构建归档形式和共享目标形式的库,我们只简要给出相关命令。关于构建这类库文件的更多信息,可以参考 gcc 的文档,包括 gcc 和 ar 的手册页。
We focus our detailed discussion of writing, compiling, and linking library code on the case in which the programmer has access to individual library modules (either the
.cor.ofiles). This focus also applies to designing and compiling large C programs that are divided into multiple.cand.hfiles. We briefly show commands for building archive and shared object forms of libraries. More information about building these types of library files is available in thegccdocumentation, including the man pages forgccandar.
通过例子了解库的细节
Library Details by Example
下面我们给出一些创建和使用自己的库的例子。
In the following, we show some examples of creating and using your own libraries.
定义库的接口:
Define the library interface:
头文件(.h 文件)是包含 C 函数原型和其他定义的文本文件——它们代表库的接口。任何打算使用该库的应用程序都必须包含这个头文件。例如,C 标准库的头文件通常存放在 /usr/include/ 中,可以用编辑器查看:
Header files (
.hfile) are text files that contain C function prototypes and other definitions — they represent the interface of a library. A header file must be included in any application that intends to use the library. For example, the C standard library header files are usually stored in/usr/include/and can be viewed with an editor:
1 | $ vi /usr/include/stdio.h |
下面是某个库的一个示例头文件(mylib.h),其中包含一些供库的用户使用的定义。
Here’s an example header file (
mylib.h) from a library that contains some definitions for users of the library.
1 | #ifndef _MYLIB_H_ |
头文件的内容外面通常包着一段特殊的「样板」(boilerplate)代码:
Header files typically have special “boilerplate” code around their contents:
译注
下面这段样板只是示意,完整的写法是 #ifndef 某个宏名 / #define 某个宏名 / … / #endif(见上面的 mylib.h),称为包含保护(include guard)。另外,C 标准把以下划线加大写字母开头的标识符(如 _MYLIB_H_)保留给编译器和标准库使用,自己的头文件用 MYLIB_H 这样的名字更规范;许多编译器也支持非标准但通用的 #pragma once 达到同样效果。
1 | #ifndef |
这段样板代码确保编译器的预处理器在任何包含 mylib.h 的 C 文件中都只把它的内容包含一次。只包含一次 .h 文件的内容很重要,可以避免编译时出现重复定义错误。类似地,如果你在使用该库的 C 程序中忘了包含 .h 文件,编译器会产生 undefined symbol(未定义符号)警告。
This boilerplate code ensures that the compiler’s preprocessor only includes the contents of
mylib.hexactly once in any C file that includes it. It is important to include.hfile contents only once to avoid duplicate definition errors at compile time. Similarly, if you forget to include a.hfile in a C program that uses the library, the compiler will generate anundefined symbolwarning.
.h 文件中的注释是库接口的一部分,是写给库的用户看的。这些注释应当详尽,解释各项定义,并描述每个库函数做什么、接收什么参数值、返回什么。有时 .h 文件还会包含一段顶层注释,说明如何使用这个库。
The comments in the
.hfile are part of the interface to the library, written for users of the library. These comments should be verbose, explaining definitions and describing what each library function does, what parameters values it takes, and what it returns. Sometimes a.hfile will also include a top-level comment describing how to use the library.
全局变量定义和函数原型之前的关键字 extern 表示这些名字是在别处定义的。对于库导出的任何全局变量,在其前面加上 extern 尤为重要,因为它把(.h 文件中的)名字和类型定义,与库实现中的变量声明区分开来。在前面的例子中,全局变量在库内部只声明一次,但通过库的 .h 文件中的 extern 定义导出给库的用户。
The keyword extern before the global variable definition and function prototype means that these names are defined somewhere else. It is particularly important to include
externbefore any global variables that the library exports, as it distinguishes a name and type definition (in the.hfile) from a variable declaration in the library’s implementation. In the previous example, the global variable is declared exactly once inside the library, but it’s exported to library users through itsexterndefinition in the library’s.hfile.
译注 · 术语提示
原书在这里对 declaration(声明)和 definition(定义)的用法与 C 标准恰好相反。按 C 标准的说法:头文件中带 extern 的 extern int total_times; 是声明(告诉编译器有这样一个变量,不分配存储空间);库实现中的 int total_times = 0; 是定义(真正分配存储空间),并且只能出现一次。
实现库的功能:
Implement the library functionality:
程序员在一个或多个 .c 文件(有时还有内部 .h 文件)中实现库。实现包括 .h 文件中所有函数原型的定义,以及实现内部使用的其他函数。这些内部函数通常用关键字 static 定义,这把它们的可用范围限定在定义它们的模块(.c 文件)内。库的实现还应当为 .h 文件中的每个 extern 全局变量声明提供变量定义。下面是一个示例库实现(mylib.c):
Programmers implement libraries in one or more
.cfiles (and sometimes internal.hfiles). The implementation includes definitions of all the functions’ prototypes in the.hfile as well as other functions that are internal to its implementation. These internal functions are often defined with the keywordstatic, which scopes their availability to the module (.cfile) in which they are defined. The library implementation should also include variable definitions for anyexternglobal variable declarations in the.hfile. Here’s an example library implementation (mylib.c):
1 | #include <stdlib.h> |
创建库的二进制形式:
Create a binary form of the library:
要创建库的二进制形式(.o 文件),用 -c 选项编译:
To create a binary form of the library (a
.ofile), compile with the-coption:
1 | $ gcc -o mylib.o -c mylib.c |
一个或多个 .o 文件可以构建出库的归档(.a)版本或共享目标(.so)版本。
One or more
.ofiles can build an archive (.a) or shared object (.so) version of the library.
- 要构建静态库,使用归档工具(
ar):
- To build a static library use the archiver (
ar):
1 | ar -rcs libmylib.a mylib.o |
- 要构建动态链接库,库中的
mylib.o目标文件必须用位置无关代码(position independent code)构建(使用-fPIC)。给gcc指定-shared标志,就可以由mylib.o生成共享目标文件libmylib.so:
- To build a dynamically linked library, the
mylib.oobject file(s) in the library must be built with position independent code (using-fPIC). Alibmylib.soshared object file can be created frommylib.oby specifying the-sharedflag togcc:
1 | gcc -fPIC -o mylib.o -c mylib.c |
- 共享目标库和归档库常常由多个
.o文件构建,例如(记住,用于动态链接库的.o需要用-fPIC标志构建):
- Shared object and archive libraries are often built from multiple
.ofiles, for example (remember that.ofor dynamically linked libraries need to be built using the-fPICflag):
1 | gcc -shared -o libbiglib.so file1.o file2.o file3.o file4.o |
使用并链接库:
Use and link the library:
在使用这个库的其他 .c 文件中:
In other
.cfiles that use this library:
#include它的头文件,并且
#includeits header file, and
- 在编译时显式链接它的实现(
.o文件)。
- explicitly link in the implementation (
.ofile) during compilation.
包含库的头文件之后,你的代码就可以调用库的函数了(例如在 myprog.c 中):
After including the library header file, your code then can call the library’s functions (e.g., in
myprog.c):
1 | #include <stdio.h> |
原书注 · #include 语法与预处理器(#include syntax and the preprocessor)
注意,包含 mylib.h 的 #include 语法与包含 stdio.h 的不同。这是因为 mylib.h 并不和标准库的头文件放在一起。预处理器有一些默认的位置用来查找标准头文件。用 <file.h> 语法而不是 "file.h" 语法包含文件时,预处理器会在这些标准位置中查找头文件。
当用双引号包含 mylib.h 时,预处理器首先在当前目录中查找 mylib.h 文件,然后再到你需要通过给 gcc 指定包含路径(-I)明确告诉它的其他位置去找。例如,如果头文件位于 /home/me/myincludes 目录(而不是和 myprog.c 文件在同一个目录),就必须在 gcc 命令行中指定这个目录的路径,预处理器才能找到 mylib.h 文件:
1 | $ gcc -I/home/me/myincludes -c myprog.c |
Note that the
#includesyntax to includemylib.his different from the syntax to includestdio.h. This is becausemylib.his not located with the header files from standard libraries. The preprocessor has default places it looks for standard header files. When including a file with the<file.h>syntax instead of the"file.h"syntax, the preprocessor searches for the header file in those standard places.When
mylib.his included inside double quotes, the preprocessor first looks in the current directory for themylib.hfile, and then other places that you need to explicitly tell it to look, by specifying an include path (-I) togcc. For example, if the header file is in the/home/me/myincludesdirectory (and not in the same directory as themyprog.cfile), then the path to this directory must be specified in thegcccommand line for the preprocessor to find themylib.hfile:
1 $ gcc -I/home/me/myincludes -c myprog.c
把使用库(
mylib.o)的程序(myprog.c)编译成二进制可执行文件:1
$ gcc -o myprog myprog.c mylib.o
To compile a program (
myprog.c) that uses the library (mylib.o) into a binary executable:
1 $ gcc -o myprog myprog.c mylib.o
或者,如果编译时能拿到库的实现文件,就可以直接用程序和库的
.c文件构建程序:1
$ gcc -o myprog myprog.c mylib.c
Or, if the library’s implementation files are available at compile time, then the program can be built directly from the program and library
.cfiles:
1 $ gcc -o myprog myprog.c mylib.c
或者,如果库以归档文件或共享目标文件的形式提供,就可以用
-l把它链接进来(-lmylib:注意库名是libmylib.[a,so],但gcc命令行中只写mylib这一部分):1
$ gcc -o myprog myprog.c -L. -lmylib
-L.选项指定libmylib.[so,a]文件所在的路径(-L后面的.表示在当前目录中查找)。默认情况下,只要能找到.so版本,gcc就会动态链接库。关于链接和链接路径的更多信息,请参见使用 C 库一节。
Or, if the library is available as an archive or shared object file, then it can be linked in using
-l, (-lmylib: note that the library name islibmylib.[a,so], but only themylibpart is included in thegcccommand line):
1 $ gcc -o myprog myprog.c -L. -lmylibThe
-L.option specifies the path to thelibmylib.[so,a]files (the.after the-Lindicates that it should search the current directory). By default,gccwill dynamically link a library if it can find a.soversion. See the Using C libraries section for more information about linking and link paths.
然后就可以运行程序了:
The program can then be run:
1 | $ ./myprog |
如果你运行的是动态链接版本的 myprog,可能会遇到类似这样的错误:
If you run the dynamically linked version of
myprog, you may encounter an error that looks like this:
译注 · 这里的错误信息放错了
下面这条 /usr/bin/ld: cannot find -lmylib 其实是编译(链接)时由链接器 ld 报的错,表示用 -L 指定的路径里找不到库文件。程序运行时找不到 .so 的报错是另一种样子,见上一节:error while loading shared libraries: libmylib.so: cannot open shared object file: No such file or directory。后面一段说的 LD_LIBRARY_PATH 解决的是运行时的这个问题。
1 | /usr/bin/ld: cannot find -lmylib |
这个错误是说,运行时链接器在运行时找不到 libmylib.so。要解决这个问题,可以设置 LD_LIBRARY_PATH 环境变量,使其包含 libmylib.so 文件所在的路径。之后运行 myprog 时,就会用你加入 LD_LIBRARY_PATH 的路径去查找 libmylib.so 文件,并在运行时加载它。例如,如果 libmylib.so 位于 /home/me/mylibs/ 子目录中,在 bash shell 提示符下运行一次下面的命令来设置 LD_LIBRARY_PATH 环境变量:
This error is saying that the runtime linker cannot find
libmylib.soat runtime. To fix this problem, set yourLD_LIBRARY_PATHenvironment variable to include the path to thelibmylib.sofile. Subsequent runs ofmyproguse the path you add toLD_LIBRARY_PATHto find thelibmylib.sofile and load it at runtime. For example, iflibmylib.sois in the/home/me/mylibs/subdirectory, run this (just once) at the bash shell prompt to set theLD_LIBRARY_PATHenvironment variable:
1 | $ export LD_LIBRARY_PATH=/home/me/mylibs:$LD_LIBRARY_PATH |