Code organization style for C?


I know some higher level languages, all web based (PHP, javascript, some python). I've finally decided to learn a lower level language, and I've decided to go with C. The problem is that all the languages I use are based heavily on OOP. Seeing as (based on the research I did) C doesn't have classes or inheritance. As a result, I ask you this: How should I organize my code in C in an organized manner like OOP, without having to switch languages or just have files with endless amounts of functions?

Edit from Future: This question is pretty silly looking back on it. I was 15 and didn't have CS at my school…

Best Solution

C doesn't offer much in the way of code organization. There's functions and files.

Whenever you want to implement an interface with hidden implementation, or perhaps with private functions, create two files, like "foo.h" and "foo.c".

The interface and/or public functions are function prototypes in "foo.h", and the functions are written in "foo.c". In addition, any hidden implementation or other private functions are in "foo.c", but marked as static, such as static int foo_internal_function(int i);. Functions marked static may only be referenced in the file they exist in, not any other.

There are no formal namespaces, although you can get much the same effect with prefixing function names, such as Foo_discombobulate_developers(). There are no classes, although you can at least get some encapsulation effects with the files. There is no extensible hierarchy, just files and functions.

C doesn't have anywhere near the organization of later languages, but lots of really good programs have been written in it. Be careful, comment anything confusing (and in C there are likely to be confusing things), and keep good notes.

Related Question