我按照以下教程创建了一个静态库。
http://tldp.org/HOWTO/Program-Library-HOWTO/static-libraries.html
http://www.adp-gmbh.ch/cpp/gcc/create_lib.html
http://www.cs.dartmouth.edu/~campbell/cs50/buildlib.html
我使用 ar
工具在 C 中生成了一个静态库。该库来自不同的目录。我正在正确生成库,并且我正在使用它来编译我的程序,如下所示:
gcc -lpthreads main.c -o server -L thread-pool -lthreadpool
当前目录下的库名为thread-pool
,其中包含libthreadpool.a
。
根据教程,我需要在 main.c
中包含我的 .h
文件:#include "threadpool.h"
。 GCC 抛出一个错误,提示未找到 threadpool.h
。这很明显,因为它位于不同的目录中。
当我包含为:#include threadpool/threadpool.h"
它编译但实际上不起作用。它仍然无法识别函数。我不确定为什么会这样.我想当编译一个静态库时,实际上你不需要实际发送.h
文件或任何源。
这里有什么问题?我该如何克服这个问题?
编辑:
我知道 .h 文件与静态库不同。我不确定为什么我上面所说的让我觉得我对两者感到困惑。
不管怎样,那么当一个人使用静态库时,是否意味着我们还需要.h
文件并将其包含到源代码中,而不是仅仅使用静态库编译程序?
最佳答案
库和 header 是两个不同(但相关)的东西。您也可以通过编译器的选项来解决您的问题,为编译器提供一个额外的目录来查找 header :
gcc -lpthreads -I threadpool main.c -o server -L thread-pool -lthreadpool
由于您的 threadpool
库可能依赖于 libpthread
,您可能需要更改编译器命令行,以便 libpthreads
出现在 之后libthreadpool
以避免链接问题:
gcc -I threadpool main.c -o server -L thread-pool -lthreadpool -lpthreads
实际上,首选选项是使用 -pthread
选项,它确保 pthread 库被正确链接,并且线程支持所需的任何其他编译器配置都已完成(顺序-pthread
选项似乎无关紧要):
gcc -pthread -I threadpool main.c -o server -L thread-pool -lthreadpool
在任何目标文件之后而不是之前列出库(例如 -lxyz
)也是一个好主意。在某些系统上,它可以双向工作;在所有已知系统上,在目标文件之后列出库总是有效的。
关于c - C 中的静态库包含问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13665698/