6 ms·
How to write generics in C
- self_awareness 1y agoWell, another option would be to use a C++ compiler, which supports templates, but limit the use of classes through a coding convention standard.
- lelanthran 1y ago> Well, another option would be to use a C++ compiler, which supports templates, but limit the use of classes through a coding convention standard. When the other option is "ask the developers to practice discipline", an option that doesn't require that looks awfully attractive. That being said, I'm not a fan of the described method either. Maybe the article could have shown a few more uses of this from the caller perspective.
- krupan 1y ago"ask the developers to practice discipline" is a baseline requirement for coding in C
- pjmlp 1y agoUnfortunately the majority has failed to attend the temple classes on such practices.
- lelanthran 1y ago> "ask the developers to practice discipline" is a baseline requirement for coding in C Sure, but since there's 10x more opaque footguns in C+++, there is much less discipline needed than when coding in C++. The footguns in C are basically signed-integer over/underflows and memory errors. The footguns in C++ include all the footguns in C, and then add a ton more around object construction type, object destruction types, unexpected sharing of values due to silent and unexpected assignments, etc. Just the bit on file-scope/global-scope initialisation alone can bite even experienced developers who are adding a new nonlocally-scoped instance of a new class.
- Loudergood 1y agoIf only.
- EPWN3D 1y agoAnd it hasn't worked in practice. C unfortunately does not have a very big pit of success -- it's way too hard to do the right thing and way too easy to do the wrong thing. The solution to this doesn't have to be "rewrite everything in Rust", but it does mean that you need to provide safe, easy implementations for commonly-screwed-up patterns. Then you're not asking people to be perfect C programmers; you're just asking them to use tools that are easier than doing the wrong thing.
- krupan 1y agoNot sure why this is down voted when the whole point of TFA is to torture the C language into doing something it can't really do. I guess there's an unspoken assumption in TFA that you are stuck using C and absolutely cannot use a different language, not even C++?
- relling 1y agoThis looks far less tortured to my eye than C++. I think a lot of us have this self-imposed rule, for whatever reason, that we absolutely will not use C++.
- pjmlp 1y agoC folks rather reproduce badly C++ than acknowledge its Typescript like improvements over C.
- lelanthran 1y ago> C folks rather reproduce badly C++ than acknowledge its Typescript like improvements over C This is a rather crude misrepresentation; most C programmers who need a higher level of abstraction than C reach for Java, C# or Go over C++. IOW, acknowledging that C++ has improvements over C still does not make the extra C++ footguns worth switching over. When you gloss over the additional footguns, it looks like you're taking it personally when C programmers don't want to deal with those additional footguns. After all, we don't choose languages based on which one offers the most freedom to blow your leg off, we tend to choose languages based on which ones have the most restrictions against blowing your leg off. If your only criteria is "Where can I get the most features", then sure, C++ looks good. If your criteria is "Where are the fewest footguns", then C++ is at the bottom of the list.
- pjmlp 1y agoNah, it is called life experience meeting those kind of persons since the 1990's, starting on BBS forums. My criteria is being as safe as Modula-2 and Object Pascal, as bare minimum. C++ offers the tools, whereas WG14 has made it clear they don't even bother, including turning down Dennis Ritchie proposal for fat pointers.
- lelanthran 1y ago>> looks like you're taking it personally > it is called life experience meeting those kind of persons Looks like you are confirming that you are taking it personally. I don't understand why, though. You cannot imagine a programmer that wants fewer footguns?
- pjmlp 1y agoYes, when careless programmers are responsible for critical infrastructure systems, and rather take a YOLO attitude to systems programming.
- flashgordon 1y agoActually this was my first instinct too. Just limit what you use c++ for and write c code with templates and be done with it. The problems I am guessing start when you are tempted into using the rest of the features one by one. You have generics. Well next let's get inheritance in. Now a bit of operator overloading. Then dealing with all kinds of smart pointers...
- eptcyka 1y agoWhat would be the detrimental effect of using smart pointers?
- flashgordon 1y agoOh i didnt mean that smart pointers were bad or detriemental. Or even that any of the other gazzilion features of C++ were bad (or detrimental) on their own. Just that C++ has sooo many features that i dont think there is any one in the world who knows who any one feature X interacts with feature Y so your ability to reason about what you have written in C++ is significantly lowered. If you can say I will only use features A, X an Z of C++ and some how enforce it then you are mitigating a lot of the risk. IIRC Carbon (Google's new lang to migrate their code off C++) came about because they themselves used C++ in a very bounded way (I recall a lot of the templates they created for their use of C++ actually resembled how Go code looked like and may have been one of the reasons for creating Go). But I am not sure how many mere mortals have that kind of tooling and discipline to limit themselves?
- 1718627440 1y agoUnclear, not explicit ownership.
- hawk_ 1y agoIs there a way to pass compiler switches to disable specific C++ features? Or other static analysis tools that break the build upon using prohibited features?
- fweimer 1y agoNo two development groups agree on the desired features, so it would have to be a custom compiler plugin. You could start with a Perl script that looks at the output of “clang++ -Xclang -ast-dump” and verifies that only permitted AST nodes are present in files that are part of the project sources.
- hawk_ 1y agoFor sure no two groups want the same subset but is there no "standard way" to opt in / out in the ecosystem? It's strange that there are large orgs like Google enforcing style guidelines but manual code reviews are required to enforce it. (or may be my understanding of that's enforced is wrong)
- pjmlp 1y agoYes, via static analysis tools it is possible. As usual with additional tooling, there must exist some willingness to adopt them.
- 1718627440 1y agoThere is -fno-rtti, -fno-exceptions, -Wmultiple-inheritance, -Wvirtual-inheritance, -Wnamespaces, -Wsuggest-final-types, -Wsuggest-final-methods, -Wsuggest-override, -Wtemplates, -Woverloaded-virtual, -Weffc++, -fpermissive, -fno-operator-names and probably many more. The warnings can be turned into errors, e.g. -Werror=namespaces.
- EPWN3D 1y agoIt never seems to work out that way though. C++ is just too large a language, and it gets bigger with each revision. The minute you hire a senior/principal engineer who loves C++, they'll make the case to enable "just this one" feature, and before you know it, you've got a sprawling C++ code base, not a "C with a light dusting of C++" code base.
- deleted 1y ago[deleted]
- schaefer 1y agoA more accurate title would be: “How to write type safe generics using the C preprocessor”
- lelanthran 1y agoHaving used this in production around 2004, I never really liked this approach - abusing the preprocessor this much shouldn't be necessary and the result is almost unreadable. I think a better way is possible using `_Generic`[1]. Even though it would still use macros, the resulting code is much more readable. --------------------------- [1] `_Generic` comes with its own problems too, of course.
- naasking 1y ago> abusing the preprocessor this much shouldn't be necessary and the result is almost unreadable. The readability of error messages was always my beef with macro-based generics. Maybe 15 years ago I played around with using UTF characters for the brackets and type separators when translating a generic type into name-mangled type, so at least the generated source and error messages would still be clear and understandable. Robust UTF support for identifiers and preprocessor was still kind of inconsistent across compilers though, so it only sort of worked. I expect this has improved considerably now though, so maybe I should try again and write something up. You can embed a surprising amount of advanced programming language theory into suitable name resolution.
- synergy20 1y agoor use nim metaprogramming, which will be transpiled to c
- david2ndaccount 1y agoI wrote a similar article in the past: https://www.davidpriver.com/ctemplates.html https://www.davidpriver.com/ctemplates.html I use this technique in my hobby projects as it has worked out the best for me of the options I’ve explored.
- variadix 1y agoYou can create macro functions per generic function so something like Vector_New(int)(&v) expands to Vector_New_int(&v). It also looks less foreign (more like templates) than the G macro.
- pjmlp 1y agoType safety, generics and C is a bit of oxymoron.
- keyle 1y agoEverything above is a fat pointer! /s
- jesse__ 1y agoI wrote a metaprogramming language that adds another option to the list, for anyone that's interested : https://github.com/scallyw4g/poof https://github.com/scallyw4g/poof
- tester756 1y agoWhy they cannot add generics to C as first class citizen, so you don't have to abuse macros, preprocessing and other primitive techniques?
- xigoi 1y agoBecause according to C programmers, generics are too “complex” (as opposed to preprocessor abuse, which is “simple”).
- uecker 1y agoThere are too complex. And having suffered from endless hours debugging C++ template code in the past, I think C's macros are actually better - if done carefully.
- kevin_thibedeau 1y agoI recommend m4 for doing this sort of thing. It's much easier to manipulate the generated source with its facilities than with the preprocessor.
- giantpotato 1y agovec_push doesnt check for realloc failure in vec_fit
- QuadmasterXLII 1y agoInstead of invisibly generating the per type headers and implementations via macros during compilation, I generate them using something like M4 and check them into the version control system. Then, instead of integrating M4 into the compilation process, I verify that the checked in generated files match the output of m4 in the CI checks. The prettiness of the generated files is now a code quality target. This provides the best possible developer experience to anyone who is not modifying the generic containers, and survivable dx if you are modifying the generic containers, at which point you kind of deserve it and any mistakes from forgetting to regenerate and re check in are isolated from other users at the CI step. This is secretly two way generation: you can edit The generated file, recompiling until until the code works, commit that, and then edit the M4 inputs until CI passes. As another example of the same principle, whenever I am required to have a requirements.txt and setup.cfg in the same puthon library, I now verify that they match in a CI check instead of trying to single source of truth by having a setup.cfg import the requirements.txt through some clever hack.
- codr7 1y agoNo. You don't mess around with the language like that. This is how you do it: https://github.com/codr7/hacktical-c/tree/main/vector https://github.com/codr7/hacktical-c/tree/main/vector
- xigoi 1y agoThis is the type erasure approach, whose cons are mentioned in the article.
- codr7 1y agoIt's the C approach, strong typing doesn't mix well with raw memory access.
- xigoi 1y agoNim is strongly typed and allows raw memory access just fine.
- deleted 1y ago[deleted]
- 1718627440 1y agoThe very article we are discussing shows you a way how to do that type safely in C. It uses #include which is a very idiomatic way to do this in C, and an example where a preprocessor-based approach is more flexible, than e.g. a module system.
- wffurr 1y agoWhy did this get flagged? Weird.
- abnercoimbre 1y agoStrange indeed. I thought maybe the article was seen as AI slop, but nothing about it suggests any such thing. It's a decent blog post.
- mistivia 1y agoI used similar method to craft my own type-safe algorithm and data structure library in C: https://github.com/mistivia/algds https://github.com/mistivia/algds Although it's a toy not for production, it's very interesting that the idea of traits/concept/typeclass just "emerge" out of the code, which made me suddenly understand why STL come into being.
- uecker 1y agoHere is my take on this: https://uecker.codeberg.page/2025-07-20.html https://uecker.codeberg.page/2025-07-20.html (you could also create a version with capacity, of course, but I like it this way).