What methods are there to modularize C code?

后端 未结 8 1632
我在风中等你
我在风中等你 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.

提交回复
热议问题