如何在 C 中创建库?

How do I create a library in C?

我正在开发一个使用 libgit2 的程序。我将代码保存在一个 c 文件中。说:

somefile.c

我自己编译使用。现在我想把libgit2相关的一些细节分离到项目内部的一个单独的库中。所以我创建了一个 h 文件,其中包含我需要的数据结构和我想使用的函数的定义。到目前为止,没有什么特别的:初始化东西,传递到 repo 的路径和 s 一个 treeish ...那些是 const * constant ...。然后在库 c 文件中我有一个 .h 文件中的函数的实现。

目前,布局是这样的:

include/mylib.c
include/mylib.h
somefile.c

include/mylib.h 中,我有一个结构和几个函数:

struct blah {} blah_info;

int blah_init(cont char * path, const char * treeish);

int blah_shutdown();

在 include/mylib.c 中我包含 mylib.h:

#include "mylib.h" # notice that I don't have to use "include" in the path

然后我定义了我放入 .h 文件中的 2 个函数。

somefile.c 中,现在我包含库 c 文件,而不是 .h 文件(并且不再需要包含 git2.h现在在 mylib 文件中完成。

#include "include/mylib.c"

这允许我编译和 运行 程序,就像我将它分成几部分之前所做的那样 但是 我知道可以包含 include/mylib.h 来自原始的 .c 文件。我认为在编译最终程序之前需要先构建库?需要哪些步骤?

现在我正在手动编译 shell 脚本,一次性调用 GCC...所以如果我需要 运行 更多命令来执行此操作,请告诉我以便我将它们添加到脚本中。

somefile.c中,你需要这样做:

#include "include/mylib.h"

并确保您 mylib.c:

中定义了这些函数
int blah_init(cont char * path, const char * treeish) {

}

int blah_shutdown() {

}

然后声明它们在mylib.h:

struct blah {} blah_info;

int blah_init(cont char * path, const char * treeish);

int blah_shutdown();

并且在编译时,将 somefile.cmylib.c 作为输入文件包括在内。

#include 指令用于在其他地方插入文件的内容,它主要用于包含 headers 以便编译器知道什么是什么(类型、常量等),然后链接器将所有已编译的文件放入成一个单一的可执行文件。 确保 header 仅包含一次到单个文件中,您使用称为条件编译的东西,它是用预处理器完成的(编译前)

yourlib.h

#ifndef YOUR_LIB_H_ //there are many naming conventions but I prefer this one
#define YOUR_LIB_H_

//all your declarations go here

#endif //YOUR_LIB_H_
//you should put in comment what's that condition for after every endif

现在在 yourlib.c 中包含 header 然后写下你的定义

#include "yourlib.h"

//all your definitions go here

你的主文件也一样,只要包含 header 编译器就知道该做什么了

#include "yourlib.h"

//your code goes here