What methods are there to modularize C code?

后端 未结 8 1615
我在风中等你
我在风中等你 2021-02-05 15:48

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

相关标签:
8条回答
  • 2021-02-05 16:18

    A function should do one thing and do this one thing well.

    Lots of little function used by bigger wrapper functions help to structure code from small, easy to understand (and test!) building blocks.

    Create small modules with a couple of functions each. Only expose what you must, keep anything else static inside of the module. Link small modules together with their .h interface files.

    Provide Getter and Setter functions for access to static file scope variables in your module. That way, the variables are only actually written to in one place. This helps also tracing access to these static variables using a breakpoint in the function and the call stack.

    One important rule when designing modular code is: Don't try to optimize unless you have to. Lots of small functions usually yield cleaner, well structured code and the additional function call overhead might be worth it.

    I always try to keep variables at their narrowest scope, also within functions. For example, indices of for loops usually can be kept at block scope and don't need to be exposed at the entire function level. C is not as flexible as C++ with the "define it where you use it" but it's workable.

    0 讨论(0)
  • 2021-02-05 16:20

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

    0 讨论(0)
提交回复
热议问题