What methods, practices and conventions do you know of to modularize C code as a project grows in size?
Modularization is a method to organize large programs in smaller parts, i.e. the modules. Every module has a well defined interface toward client modules that specifies how "services" provided by this module are made available.
Modularity is closely tied with encapsulation; think of modularity as a way of mapping encapsulated abstractions into real, physical modules. The C/C++ convention is to create two files for each class: a header file (. h suffix) for the class interface, and an implementation file (.
Modular programming usually makes your code easier to read because it means separating it into functions that each only deal with one aspect of the overall functionality. It can make your files a lot smaller and easier to understand compared to monolithic code.
Create header files which contain ONLY what is necessary to use a module. In the corresponding .c file(s), make anything not meant to be visible outside (e.g. helper functions) static. Use prefixes on the names of everything externally visible to help avoid namespace collisions. (If a module spans multiple files, things become harder., as you may need to expose internal things and not be able hide them with "static")
(If I were to try to improve C, one thing I would do is make "static" the default scoping of functions. If you wanted something visible outside, you'd have to mark it with "export" or "global" or something similar.)
OO techniques can be applied to C code, they just require more discipline.
stdio
library -- everything is organised around the opaque FILE*
handle. Many successful libraries are organised around this principle (e.g. zlib, apr)struct
s are implicitly public
in C, you need a convention + programmer discipline to enforce the useful technique of information hiding. Pick a simple, automatically checkable convention such as "private members end with '_'".If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With