制作库程序通常涉及以下步骤:
编写库文件
创建一个不含`main()`函数的源文件,例如`libHelloWorld.cpp`,并提供一些函数供其他程序调用。
创建库
使用CMake的`add_library`命令来创建库。例如,在`CMakeLists.txt`中添加`add_library(hello libHelloWorld.cpp)`,这将编译`libHelloWorld.cpp`并创建一个名为`hello`的静态库(`.a`文件)或动态库(`.so`文件)。
编译库
运行`cmake`命令来配置项目,并使用`make`命令来编译库。例如,在终端中输入`cd build && cmake .. && make`来编译库文件。
链接库
在需要使用该库的程序中,使用`-l`选项来链接库。例如,在`main.c`中添加`-lhello`来链接名为`hello`的库。如果库位于特定路径,可以使用`-L`选项指定路径,如`-L/path/to/library`。
使用库
在程序中包含库的头文件,并调用库中的函数。例如,在`main.c`中包含`include "hello.h"`,然后调用`hello_function()`。
示例
假设我们要创建一个名为`MathFunctions`的库,包含一个名为`mysqrt`的函数。以下是详细步骤:
创建库文件
在`MathFunctions`子目录下创建`mysqrt.cxx`和`mysqrt.h`文件,分别包含`mysqrt`函数的实现和声明。
创建库
在`MathFunctions`子目录的`CMakeLists.txt`中添加以下命令:
```cmake
add_library(MathFunctions mysqrt.cxx)
```
编译库
在项目根目录下运行以下命令:
```sh
cd MathFunctions
cmake .
make
```
这将生成一个名为`libMathFunctions.a`(静态库)或`libMathFunctions.so`(动态库)的文件。
链接库
在需要使用`MathFunctions`库的程序中,使用以下命令链接库:
```sh
gcc main.c -L/path/to/MathFunctions -lMathFunctions
```
使用库
在程序中包含库的头文件,并调用库中的函数:
```c
include "MathFunctions/mysqrt.h"
int main() {
double result = mysqrt(16);
printf("Square root of 16 is %f\n", result);
return 0;
}
```
通过以上步骤,你就可以成功创建并使用一个库程序了。