A couple of things recently got me thinking about design patterns in C.

Now, classic programming design patterns are language agnostic, although many are implicitly object-oriented. What I am discussing here are C-language-specific design patterns to achieve certain things when C programming (or to circumvent C-specific design problems).

I thought I would try to enumerate some here.

singleton headers

In C, you cannot redefine a type.

16:45:31$ cat > foo.c
struct foo { int x; };
struct foo { char c; };
int main() { return 0;} 
16:45:54$ cc -Wall foo.c
foo.c:2: error: redefinition of ‘struct foo’

You usually define types within header files. Sometimes, you need to refer to a type in a header file which does not define it: in which case, you include the former header in the latter.

Once header files start including other header files, it's quite easy to end up in a situation where the same header file is included more than once. To avoid this type redefinition problem, many people use the C pre-processor to ensure the contents of the header are only included the first time:

#ifndef SOME_HEADER_H
#define SOME_HEADER_H
/* type definitions go here */
#endif
This page is a draft.