头文件中的 C 函数实现
C function implementations in header files
我正在用 C 实现一些数据结构,目标是能够在未来的项目中轻松使用它们。
一种可能的方法是在头文件中实现每个数据结构。
例如这里是linked_list.h:
#ifndef LINKED_LIST
#define LINKED_LIST
#include <stdlib.h>
typedef struct linked_list_type {
int val;
struct linked_list_type* next;
} linked_list;
// Initializes a single node with a value v
linked_list* ll__init(int v) {
linked_list* new_ll = malloc(sizeof(linked_list));
new_ll->val = v;
new_ll->next = NULL;
return new_ll;
}
// More functions
#endif
这很好用,因为我可以在未来的项目中使用 #include "linked_list.h"
获取 linked_list 结构及其所有函数。
但是,这违背了在头文件中仅使用声明(而不是实现)的常规做法。所以,我有一些问题:
- 有没有更好的方法来获得像这样简单的内含物?通过一些搜索,包含 .c 文件似乎不是一个好主意。
- 我现在正在做的事情 bad/dangerous 是我没有意识到的方式吗?
关于您的第一个问题,标准方法是 link 代码,可以是另一个 .c
文件的形式,也可以是静态库。但您也可以对所有内容使用 inline
。 (虽然我认为这不是大型数据结构的好解决方案。)
关于你的第二个问题,一个危险是,如果你试图 link 将两个(或更多)使用此 header 文件。 ll_init
符号将由每个 .o
文件定义。
你提醒了我 blaze math library. It is quite fast math library which uses only headers. So, yeah. You can put all implementations in headers with lots of inline
. But compilation will be a bit slower. As I remember, godbolt online compiler 经常因 blaze 而超时。
我正在用 C 实现一些数据结构,目标是能够在未来的项目中轻松使用它们。 一种可能的方法是在头文件中实现每个数据结构。
例如这里是linked_list.h:
#ifndef LINKED_LIST
#define LINKED_LIST
#include <stdlib.h>
typedef struct linked_list_type {
int val;
struct linked_list_type* next;
} linked_list;
// Initializes a single node with a value v
linked_list* ll__init(int v) {
linked_list* new_ll = malloc(sizeof(linked_list));
new_ll->val = v;
new_ll->next = NULL;
return new_ll;
}
// More functions
#endif
这很好用,因为我可以在未来的项目中使用 #include "linked_list.h"
获取 linked_list 结构及其所有函数。
但是,这违背了在头文件中仅使用声明(而不是实现)的常规做法。所以,我有一些问题:
- 有没有更好的方法来获得像这样简单的内含物?通过一些搜索,包含 .c 文件似乎不是一个好主意。
- 我现在正在做的事情 bad/dangerous 是我没有意识到的方式吗?
关于您的第一个问题,标准方法是 link 代码,可以是另一个 .c
文件的形式,也可以是静态库。但您也可以对所有内容使用 inline
。 (虽然我认为这不是大型数据结构的好解决方案。)
关于你的第二个问题,一个危险是,如果你试图 link 将两个(或更多)使用此 header 文件。 ll_init
符号将由每个 .o
文件定义。
你提醒了我 blaze math library. It is quite fast math library which uses only headers. So, yeah. You can put all implementations in headers with lots of inline
. But compilation will be a bit slower. As I remember, godbolt online compiler 经常因 blaze 而超时。