Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What methods are there to modularize C code?

What methods, practices and conventions do you know of to modularize C code as a project grows in size?

like image 709
Ari Ronen Avatar asked Jul 22 '09 03:07

Ari Ronen


People also ask

What is meant by modularization in C?

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.

How is modularity introduced in C?

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 (.

Why do we modularize code?

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.


2 Answers

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.)

like image 120
smcameron Avatar answered Oct 24 '22 00:10

smcameron


OO techniques can be applied to C code, they just require more discipline.

  • Use opaque handles to operate on objects. One good example of how this is done is the stdio library -- everything is organised around the opaque FILE* handle. Many successful libraries are organised around this principle (e.g. zlib, apr)
  • Because all members of structs 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 '_'".
  • Interfaces can be implemented using arrays of pointers to functions. Certainly this requires more work than in languages like C++ that provide in-language support, but it can nevertheless be done in C.
like image 20
j_random_hacker Avatar answered Oct 24 '22 00:10

j_random_hacker