C is barebones and “doesn’t support” generics, but it’s actually quite easy to implement with the tools we already have. There’s many ways you might find them being implemented in the wild. Some of the common ones are: Using function-like macros #define vector_push(vector, item) vector.buf[vector.idx++] = item; Con: This will cause everything to be inlined and loosely typed. void vector_push(Vector vec, void *item); Con: You rely on type erasure to achieve generics, so you’ll have to recast everything back to access them. You might also run into UB. Dispatch specializations through a function-like macro #define DECLARE_VECTOR(type) \ void vector_push(Vector##_##type, type item) {\ // do stuff here \ } DECLARE_VECTOR(int) Con: Everything is wrapped in a macro and might break autocomplete The approach I recommend is not really novel, but it’s the one I’ve found to be the nicest to use and to work better with existing tooling. Since it doesn’t rely on type erasure and everything isn’t wrapped in macros. Pros: Type safe Doesn’t have to use pointers Minimal use of Macros Can be deduplicated by linkers Can be entirely put in a single file to reduce changes triggering compilation for multiple files Cons: Relies on a macro trick Can be a bit verbose Achieving generics through header instantiation The way this works is, you instantiate a specialization for a type by defining your type and possibly a suffix if the that type is not a valid name for an identifier. To do this, we’ll have to rely on a small macro trick, but other than that, everything is quite straight forward. The header instantiation should look like this: #define VEC_ITEM_TYPE long long #define VEC_SUFFIX num #include "vector.h" With the VEC_SUFFIX being optional. Once instantiated this would give you a vector_push_num function you could use. To do this we need to be able to append _num to our symbol names. For we create a G function-like macro. #define G(name) name##_##VEC_ITEM_TYPE Except, this doesn’t work....
First seen: 2025-11-15 14:55
Last seen: 2025-11-15 15:55