Arranging Source and Header Files (the C Way)

Resourceful Code Reuse — by Dmitry Zinoviev (11 / 20)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Chapter 1 Reuse Code at Compile Time (C and Python) | TOC | Modularizing Code (the Python Way) 👉

Proper code reuse can be challenging because it requires a specific mind-set. A common mistake that even professional programmers make is putting all their code in the same file like this:

jsontool.c

​1: ​#include <stdio.h>   // For input/output​
​- ​#include <stdlib.h> // For EXIT_SUCCESS or EXIT_FAILURE​
​- ​#include <stdbool.h> // For bool, false, and true​
​-
​5: ​typedef​ ​struct​ JSON_Object {
​- ​// Lots of lines of code here​
​- ​// ...​
​- } JSON_Object;
​-
​10: ​// Lots of helper functions, data types, and global variables​
​- ​int​ json_errno = 0;
​- bool ​read_boolean​(​FILE​* infile) { ​/* ... */​; ​return​ false; }
​- ​char​ *​read_string​(​FILE​* infile) { ​/* ... */​; ​return​ NULL; }
​- ​void​ *​obscure_helper​() { ​/* ... */​ ; ​return​ NULL; }
​15: ​// ...​
​-
​- ​// JSON parser and writer​
​- JSON_Object *​read_json​(​char​ *fname) {
​- JSON_Object *object = NULL;
​20: ​// Lots of lines of code here​
​- ​// ...​
​- ​return​ object;
​- }
​-
​25: ​int​ ​write_json​(​char​ *fname, JSON_Object *object) {
​- ​int​ status = 0;
​- ​// Lots of lines of code here​
​- ​// ...​
​- ​return​ status;
​30: }
​-
​- ​// Business logic​
​- ​static​ JSON_Object *​do_stuff​(JSON_Object *json) {
​- ​// Lots of lines of code here​
​35: ​//…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.