8 ms·
Object-oriented Programming with ANSI-C (1993) [pdf]
- moth-fuzz 3y agoOne thing that's bothered me for a few years about Object-Oriented code, is the question of why the dichotomy of 'implementation' vs 'interface' is drawn on the exact same line as 'variables' and 'functions'. Everyone who's ever worked in a functional programming languages knows that functions can easily be considered 'state', and everybody who's spent time in real-life plugging in various electronic devices knows that data itself can be considered an 'interface'. So why does OOP dogma conflate these ideas together? Why couldn't a single variable or property be virtual and polymorphic? Why couldn't a member method be reassignable like a member variable? The philosophy and the actual implementations just self-reference each other. Interfaces are great because they keep interfaces separate from state. I agree. But strictly in terms of language features, why are functions considered interface while variables are considered state? Well, because that's just how they're defined, I guess. But if you're doing OOP in C, and you have a VTABLE full of pointers, well, it doesn't really matter what those pointers point do, do they? They could be function pointers, they could be variables/memory locations, they could even be references to other structs. It's not quite as delineated when you do it from the bottom up.
- rramadass 3y agoNot quite sure what you are trying to say here; but ... > the dichotomy of 'implementation' vs 'interface' is drawn on the exact same line as 'variables' and 'functions'. That's not true; They are orthogonal to each other. OOP is just a way of structuring Procedural/Imperative programming; "variables" maintain state while "functions" change/read state. You are just bundling them together to gain fine-grained modularity. An "interface" is anything (i.e. can be both variables and functions) which is "publicly" accessible by a client. An "implementation" is conversely not accessible by the client (i.e. encapsulated) but can also consist of "variables" and "functions". > Why couldn't a single variable or property be virtual and polymorphic? Not sure what you mean here but you do have tagged unions/variants/sum types which gives you what you maybe looking for. > Why couldn't a member method be reassignable like a member variable? It is possible in certain object models. Lookup "Metaclasses" in your favourite language for possible support. If you want to see example code in C++, checkout the classic Advanced C++ Programming Styles and Idioms by James Coplien. The book contains lots of examples of mind-bending OO trickery using C++.
- gyrovorbis 3y agoThis book is an absolute classic. I came from C++20, using concepts and constraints, doing a lot of compile-time metaprogramming and shenanigans, and I set off on a quest to rewrite a lot of my core tech stack in plain ol' C ('17 revision) for language interoperability reasons... ...and I literally almost gave up on being a C programmer because of bashing my head against language limitations... This book completely and totally changed everything and is the reason I completed this very ambitious project (https://github.com/gyrovorbis/libgimbal https://github.com/gyrovorbis/libgimbal)... It's not just good for object-oriented C, but also for approaching the C language differently in general. For pushing its boundaries rather than accepting its limitations. Anyway, this "PDF" was such an inspiration on me as a C programmer that I managed to track down a physical copy on Ebay. lol.
- jjgreen 3y ago(1993)
- Tomte 3y agoThanks!
- gjvc 3y agounlikely to be 2023, now, is it?
- omgmajk 3y agoWould be interesting if it was actually. Kinda feel like playing with this for fun.
- wtetzner 3y agoHere's a new library that provides OOP in C: https://github.com/gyrovorbis/libgimbal https://github.com/gyrovorbis/libgimbal
- omgmajk 3y agoCool, will look at it for inspiration :)
- gyrovorbis 3y agoI'm the author of the libGimbal project linked to there. It's a massive object-oriented C codebase with an entire cross-language type system that was inspired by GTk's GObject, Microsoft COM, and the Objective-C language. I've studied everything out there on achieving OOP in C, and actually the OP's book reference was my original inspiration. There's a fine art to doing it and a few good codebases are out there that do it well... The entire GNOME stack is based on this kind of stuff. Anyway let me know if you have any questions. lol.
- 3y ago
- aninteger 3y agoAnd for people who took this to the "next level" just look at GTK.
- gyrovorbis 3y agoExactly. Amen. GTk is the shining proudest most epic achievement of object-oriented C programming, and they still enjoy massive benefits in terms of being able to interop with every language ever because of this approach.
- pjmlp 3y agoThat would have been Motif and CDE, which Gtk is based on as idea.
- jandrese 3y agoNo seriously, the GTK C bindings are basically written in a half-formed version of the old C++ "C with preprocessor macros" syntax. It looks like this when you program it: GtkWidget* grid = gtk_grid_new(); GtkWidget* label = gtk_label_new("Hello World"); gtk_grid_attach(GTK_GRID(grid), label, 0, 0, 1, 1); That GTK_GRID bit is a macro that evaluates at runtime and will chuck out runtime errors if the widget doesn't match. It supports inheritance. If you have for example a gtk_combo_box_text, you can use gtk_combo_box_set_active(GTK_COMBO_BOX(my_combo_box_text), 0) and it will select the first entry in the gtk_combo_box_text because gtk_combo_box_text inherits from gtk_combo_box like any good object oriented system.
- gyrovorbis 3y agoI'm a huge academic fan of what GTk has accomplished (thanks to their GObject type system), and as much as I know the C89 crowd who thinks macros are all evil probably abhor this kind of thing, I think GTk is one of the most epic, impressive, ambitious C codebases in existence. Witness as non-OO C matches, rivals, and quite often beats Qt on equivalent classes/features in plain C... It's even above "just C++ style C," as they have added features like a property and signal system... I'm such a fanboy it inspired my own type system and massive core library, libgimbal, which uses a type system similar to GObject and targets game consoles like the Sega Dreamcast: https://github.com/gyrovorbis/libgimbal https://github.com/gyrovorbis/libgimbal.
- chmaynard 3y agoThis reminds me of a course I took at Stanford around 1991. The course title was UNIX C Programming and the instructor was Dr. Eric Roberts. The programming part was to build a library of simple tools and the UI was the command-line. We didn't call it object-oriented but it involved programming with ADTs that had well-defined APIs.
- zabzonk 3y ago> I could not forge a portable implementation in C++. i would like to know why not.
- kenjackson 3y agoI suspect the state of the compilers in 1993. And maybe the standard even. When I was using C++ a lot in 2000 it was difficult to get non-trivial code working across compilers.
- zabzonk 3y agocertainly true (first c++ standard was in 98) but i think this is more a library issue than anything else, which isn't germain to this article. i haven't read the article in depth, but things like new/delete, constructors and virtual functions in wide use in 93. and let's not forget that C itself was only standardised in 89, and it took vendors a long time to catch up with that standard.
- jamesfinlayson 3y agoLibrary issue was my understanding - the Half-Life mod Natural Selection used the STL heavily and was built for both Windows and Linux (Linux for dedicated servers). When the source code was released many years later the documentation said it needed a library called stlport - some third-party implementation of the STL because even in 2002 when Natural Selection was released, different compilers apparently shipped STLs of varying quality.
- zabzonk 3y agoi don't know about the half life stuff. stlport was (is?) a portable implemrntation of the Standard Template Library. this is far from the same as the C++ Standard Library.
- jamesfinlayson 3y agoIt was only used by one of the bigger Half-Life mods (nothing first party - Half-Life's game code is very much C with classes). Possibly other mods used it but I suspect that most Half-Life mods kept to the style of the original.
- 1bent 3y agoOOP has always felt to me like it was inspired by writing GUI APIs; Sun's Suntools -> Sunview -> xview (if I'm remembering the names right) were early-mid 1980s C, and felt beautifully OO, and very clean to write GUI programs. I enjoyed writing image analysis and manipulation in them. Never used the successor "intrinsics-based" Motif and CDE, the code was yucky. Didn't write another GUI until I did a dashboard (for automated software deployment) in TCL/Tk. But yeah, C++ never interested me for OO, C was fine.
- WoodenChair 3y agoI skimmed the first couple of chapters and the syntax you have to go through to make this work looks painful at best. void * everywhere. Structs with C's function pointer syntax all over the place... It looks like it can certainly work, but it's not going to be pleasant compared to almost anything designed for OO.
- rectang 3y agoYou’re right about the syntax becoming extremely tedious. Eventually you wind up doing waaaay too many function pointer casts and typedefs. The appeal of this approach, to me, is mostly pedagogic rather than practical: stuff designed for OOP isn’t generally going to let you control struct layout to the degree that C will, making it harder to get your hands dirty and learn core concepts.
- G3rn0ti 3y agoYou don’t need all that to emulate objects in C. Instead use this recipe: - classes <-> compilation units - objects <-> structs - methods <-> functions receiving a pointer to a struct as first argument; use name of the class as prefix e.g. Point3D_scale(Point3D *self, double factor) - constructors are just methods and initialize the struct - destructors are just methods and free all memory occupied by the struct Inheritance is a bit more difficult this way but as others pointed out already it is way over used IMHO. But if you really want to do that you could design a child class by using a struct pointing to the parent struct and using that to manually delegate all inherited method calls to the parent. You could probably write a fancy macro automating this delegation for you.
- ChrisMarshallNY 3y agoI did “false object” programming with C, back in the mid-90s. I never read this book, but we came up with similar approaches. I got the idea from QuickDraw GX. I passed around structs, as “nouns,” and some had built-in “verbs.” I used function pointers, and these created kind of a “poor man’s vtable.” Not exactly “polymorphism,” but similar. I needed to do it for a modular imaging peripheral SDK. Back then, the only reliable way to cross an external module boundary was with ANSI C (stack conventions). It worked quite well, as they were still using the same SDK, 25 years later. WFM. YMMV.
- edgyquant 3y agoI went through an “OOP in C” phase when I first got into C years ago. This stack overflow[1] helped a lot as well 1. https://stackoverflow.com/questions/351733/how-would-one-write-object-oriented-code-in-c https://stackoverflow.com/questions/351733/how-would-one-wri...
- jupp0r 3y agoIt's weird that so much of OOP back then was centered around deep class inheritance hierarchies as a means to share code when my favorite more modern languages (Rust and Go) intentionally leave out this part of OOP (thankfully, imho). An eye opener in respect to this was Sean Parent's excellent talk "Inheritance Is The Base Class of Evil" at GoingNative 2013 [1]. [1] https://www.youtube.com/watch?v=2bLkxj6EVoM https://www.youtube.com/watch?v=2bLkxj6EVoM
- rramadass 3y agoI really don't get why people keep repeating "class inheritance hierarchies are bad". If one understands Implementation vs. Interface inheritance and the intent behind each (the former strongly couples the code while the latter does not) then one can judiciously use inheritance techniques correctly. I recommend a study of Bertrand Meyer's OOSC2 and language Eiffel - https://en.wikipedia.org/wiki/Object-Oriented_Software_Construction https://en.wikipedia.org/wiki/Object-Oriented_Software_Const...
- gyrovorbis 3y agoIt's just the latest hipster language trend. When OO was new, structural C was evil. When functional programming happened, everything before that was evil... Because, yes, sharing state among classes for code reuse, is fundamentally evil... How dare you want to couple state and logic? Almost like every single UI framework in every mainstream language has converged upon OO as the best way to model the problem at hand... GTk even invented a similar type system to what was mentioned in this PDF just to give C OOP constructs... Now witness as the Rust language has failed to produce a compelling UI/widgeting framework or paradigm, and the best ones out there are Qt-based or GTk-bindings (letting C hilariously handle the OOP for Rust).
- rramadass 3y ago>It's just the latest hipster language trend. When OO was new, structural C was evil. When functional programming happened, everything before that was evil... Right. By any measure OOD/OOP has been enormously successful in the real world and hence it is annoying to see blanket statements like "OOD/OOP/Inheritance/etc. is bad" on HN (i expected better). It is one thing to discuss cautions/caveats/different approaches but to dismiss the whole thing is quite silly. Hence my attempt at edification of the readers :-)
- rectang 3y agoI read this whole book maybe 15 years ago. I don’t remember much detail at this point and the project I was working on at the time has been retired. Still, I have fond memories of the learning process. Manually building up single inheritance OOP with structs and vtables using C is very educational.
- alfiedotwtf 3y agoCan't find the link now, but there was some malware recently (maybe under 3 years ago) that was found to directly use this book as a basis for their code.
- nielsbot 3y agoIf you find this kind of stuff interesting, definitely take a look at this paper by Ian Piumarta: https://www.piumarta.com/software/id-objmodel/objmodel2.pdf https://www.piumarta.com/software/id-objmodel/objmodel2.pdf An OOP object model you can implement in C where the model is open and extensible inside the user environment. It's a very minimal yet flexible system.
- gyrovorbis 3y agoReminds me a lot of the magic that is the Objective-C runtime. Fantastic paper. Thanks for sharing.
- Tomis02 3y agoAs far as I can tell, the author says that "ANSI-C is a full-scale object-oriented language" in a slightly sarcastic tone, as there's nothing particular to OOP languages that you can't do in C. But I've heard many people say (and mean it) they do OOP in C. I find it a bit dubious to claim you're doing OOP in C, considering that C does not have objects. And I find it twice as dubious because you can translate any FP/OOP code to procedural C; at this rate, you can start claiming that your x86 binary is OOP. I often hear that "FILE is an object, it's exactly as if C++ had class FILE {...}, the class is just syntactic sugar, the result of the compilation is identical". This is false, as it's not "just syntactic sugar". A C++ class binds a function to a specific struct, and the function can "belong" to no other struct. When doing OOP you have to choose - function F belongs to either object A or to object B. It can't belong to both. Which is why OOP has endlessly silly discussions about whether class Car should Turn() the class Wheel, or should the class Wheel Turn() class Car. Or should we refactor it into class SteeringWheel that will Turn() both Car and Wheel. This is not a thing in C. Linus Torvalds can add a function F that operates on the internals of both FILE and DIR at the same time, for example, and suddenly it's less clear who "owns" F and which one is the object. Which is why, personally, I don't think doing dynamic dispatch with void* in C can be qualified as OOP, it's just a pattern that's been there ever since the language was introduced. It's only after you add specific OOP features to the language that it devolves into an OOP language.
- ameminator 3y agoHowever, one CAN do "object-oriented" programming in C. There are ways of modeling what a piece of data is (a struct with its members). There are ways of modeling how a piece of data can behave (functions operating on those structs/pointers to structs). Perhaps this is lacking in features and expressiveness compared to OOP-first languages like C#, C++ and others, but object-oriented concepts can apply in C - look to the compiler to organize private, public functions and ownership.
- Tomis02 3y agoI agree that you can _imagine_ that FILE and DIR are objects, you can imagine they have behaviour, you can apply your OOP mental model to procedural code. But it all breaks down the moment you add a function that operates on the internals of both FILE and DIR, because this function doesn't belong to any one object. And if you don't notice it, you keep thinking FILE and DIR are objects, when in fact they're not (a method can't "belong" to two objects, at least as far as objects are perceived in the software world). In short, I can agree that it's possible to write C with a OOP mindset. But (let's call it) imaginary OOP may not be actual OOP (as when enforced by the C++ compiler).
- vaughan 3y agoI've actually started preferring the `action(subject, object)` form of programming which OO in C entails, rather than `subject.action(object)`. The latter is certainly easier for discovery via auto-complete (with most current tooling). OO is not a natural way of programming. Everything always starts simply with functions that take arguments. Then you have a function that calls another function with some of the old arguments and some new ones. Most people go: let's make the shared param an instance var. const config = {} foo(config) function foo(config) { bar('bar', config) } bar(str, config) { ... } becomes... class MyClass { config constructor(config) { this.config = config } foo() { this.bar('bar') } bar(str) { ... } } The problem with a class, is that every method of the class potentially depends on every other member of the class. What usually happens is that stuff is added to the class that doesn't make sense. And every class needs a noun to name it. Then you have to think what is the proper name for this abstract thing you don't even know what it is yet. Which leads to all these quirky class names that are unnecessary. If you are explicit about what data dependencies each function has, it becomes easier to see the commonality that should be extracted into classes. Most people just shove everything in a class too soon. And most languages push you to use classes and methods...which usually look very different to how functions are represented.
- gpderetta 3y agoI completely agree with this. When designing classes it is very easy to get carried away and incrementally add bits to the class instead of passing dependencies explicitly. Arguably even config is too much and generally functions should only take the subset of config. In the end this is more art than engineering: classes allow encapsulating all state that needs to be used by all functions together; but as you start making exceptions you'll end up with the mess you describe. The art is finding the right balance between what goes in a class and what should be a standalone (possibly generic) function. Personally, I'm still far from mastering that art. Alexander Stepanov has a lot to say about this.
- vaughan 3y agoThere is definitely an art to it at some point, but I see a lack of tools to be a big problem. We are in the stone-age of programming at the moment. I think the solution is visualization. I want to click on any variable, and see its full data-dependency graph. All the functions it flowed through and all the transformations that occurred all the way back to a single source of truth. With this in hand, I think it would be much easier to understand how to group methods and state. We should write code such that this data-dependency graph is easily understood by humans.
- synergy20 3y agoyou can add oop to C just fine, as this paper shows. it is hard or impossible to do RAII in C, or something like defer in golang. we need both.
- stefantalpalaru 3y ago[dead]
- zzbn00 3y agoThe C Object System looks like an interesting way of doing this today: https://github.com/CObjectSystem/COS https://github.com/CObjectSystem/COS and https://arxiv.org/pdf/1003.2547.pdf https://arxiv.org/pdf/1003.2547.pdf
- pixelfarmer 3y agoThe Linux kernel contains a lot of C OOP, similar to GTK and other such frameworks. As soon as you need bindings done during runtime, you will end up with structs containing function pointers as some sort of interface descriptor, and potentially that is embedded or aligned with structs containing data. This is at least OOP class level functions with data they can operate on and if you allocate the "ops" struct (together with data) as well we are talking actual object instances. The Linux kernel is full of such things, plus there are even macros to cast up/down the inheritance tree.