Coming from an OOP background, what would be some C programs/libraries to help me get the "C way"?

181 views Asked by At

I have been doing OOP (C++/Java/PHP/Ruby) for a long time and really have a hard time imagining how large programs and libraries such as Linux or Apache can be written entirely in an imperative style. What would be small open source C projects I could look at to get a feel of how things are done in C?

Bonus points if the project is hosted on GitHub.

4

There are 4 answers

0
Chris Becke On

Things are done exactly the same way in C, but with less overt support from the language. Instead of creating a class to encapsulate some state, you create a struct. Instead of creating class members, with implicit this parameters, you create functions that you explicitly pass a struct* as the first parameter, that then operate on the struct.

To ensure that encapsulation is not broken you can declare the struct in a header, but only define it in the .c file where it is used. Virtual functions require more work - but again, its just a case of putting function pointers in the struct. Which is actually more convenient in C than C++ because in C you get to fill in your vtables manually, getting quite a fine level of control over which part of code implements part of what COM interface (if you are into COM in C of course).

0
leander On

You might find the ccan (Comprehensive C Archive Network, modeled after Perl's CPAN) interesting.

It's small at the moment, but the contributions are of high quality. Many of the contributions are by linux kernel developers.

Almost everything in there falls into the "few thousand LOC" or less category, too.

0
bta On

If you want a small example to start with, try looking at the source for the basic Linux CLI utilities. GNU binutils, make, or any of the other GNU utilities have full source code available and are relatively small code bases (some are larger than others). The easiest thing is usually to start with a utility that you have used before and are already familiar with.

0
Karl Bielefeldt On

Look at GLib for an almost canonical example of how to do object oriented programming in C.