Reputation: 1314
I am implementing some data structures in C, with the goal of being able to use them easily for future projects. One possible way to do this is to implement each of the data structures in a header file.
For example, here is 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
This works nicely, since I can just use #include "linked_list.h"
to get the linked_list struct and all its functions in a future project.
However, it goes against the normal practice of just using declarations (and not implementations) in a header file. So, I have some questions:
Upvotes: 2
Views: 140
Reputation: 1035
You reminded my about 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 often timeouted for me with blaze.
Upvotes: 0
Reputation: 4490
Re your first question, the standard way is to just to link the code, either in the form of another .c
file or in a static library. But you could also use inline
for everything. (I don't consider this a good solution for larger data structures though.)
Re your second question, one danger is that you will get a linker error if you try to link together two (or more) compiled files that have been separately compiled using this header file. The ll_init
symbol will be defined by each .o
file.
Upvotes: 2