Object Oriented C Programming Style

Naming Conventions

Naming conventions can help make APIs easier to understand and remember. The following describes some conventions I’ve adopted for writing C code in an object oriented style. These conventions are similar to those used in OO languages such as Smalltalk and Objective-C.

Whitespace

All code below should adhere to the same whitespace rules. This will make regex searching for particular items in an editor possible. For example, a function definition should have the function name defined on the first character of a new line. A structure’s true name should be a new line with a prefix of a ‘}’ char and a space. No tabs should be used at all.

Structures

Member names are words that begin with a lower case character with successive words each having their first charater upper cased. Acronyms are capitalized. Structure names are words with first character capitalized. Example:

typdef struct { char *firstName; char *lastName; char *address; } Person;

Header Files

As much as possible, only declarations should be in header files. This will allow us to only use opaque pointers when working with structures.

Functions

Function names begin with the name of structure they operate on followed by an underscore and the method name. Each structure has a new and free function. Example:

List *Listnew(void); void Listfree(List *self);

Example implementation of new and free functions:

List * Listnew(void) { List *self = (List *)calloc(1, sizeof(List)); self->items = malloc(LISTDEFAULT_SIZE); return self; }

void List_free(List *self) { free(self->items); free(self); }

Aside from new methods, all methods have the structure(the “object”) as the first object with the variable named “self”. Method names are in keyword format. That is, for each argument, the method name has a description followed by an underscore. The casing of the descriptions follow that of structure member names. Examples:

int Listcount(List self); / no argument */ void Listadd(List self, void *item); / one argument */ void Dictionarykeyvalue(Dictionary *self, char *key, char *value);

Defines

Defines are all caps words that are seperated by underscores. Define names always begin with the name of the structure that they are most closely related to. Examples:

define LISTDEFAULTSIZE 8

define LISTRESIZEFACTOR 2

File Names

Each structure has it’s own seperate .h and .c files. The names of the files are the same as the name of the structure. These files contain all the functions(methods) that operate on the given structure.

This guide was inspired by an original article by Steve on the topic of OO code style in C. I’m extending it with a few other style guidelines.