APIs, errors & testing
11 steps in 4 sets of C.
How to write C that other people can use. Function signatures that say what they mean, opaque pointers for encapsulation, error returns and cleanup paths that do not leak on the third early exit.
Eleven steps on the difference between C that compiles and C that belongs in a library.
Signatures
- Error codes and out-parametersThe C convention: return success or failure, deliver the value through a pointer.
- Guard clausesValidate at the top and return early, so the body has no nesting left.
- Bounded interfacesTake the buffer and its capacity together, and report what was needed.
- Reading versus writing APIsconst in the signature says whether a function will change what you hand it.
Encapsulation
- Opaque handlesThe header declares an incomplete type, so callers cannot see the fields.
- Init and destroy pairsEvery resource gets an init that can fail and a destroy that cannot.
- Keeping helpers privatestatic at file scope hides a function from every other translation unit.
Errors & cleanup
- An error enumNamed error codes read better than magic numbers, and map to messages.
- One exit, everything freedThe acquire-check-goto pattern, written out in full.
Encore
- Assert-based testsA test is a function full of asserts, called from main. No framework needed.
- adt_stack.cAn abstract data type done properly: opaque handle, error enum, tests in main.