What are the most common naming conventions in C?
The most important thing here is consistency. That said, I follow the GTK+ coding convention, which can be summarized as follows:
- All macros and constants in caps:
MAX_BUFFER_SIZE
,TRACKING_ID_PREFIX
. - Struct names and typedef's in camelcase:
GtkWidget
,TrackingOrder
. - Functions that operate on structs: classic C style:
gtk_widget_show()
,tracking_order_process()
. - Pointers: nothing fancy here:
GtkWidget *foo
,TrackingOrder *bar
. - Global variables: just don't use global variables. They are evil.
- Functions that are there, butshouldn't be called directly, or haveobscure uses, or whatever: one or moreunderscores at the beginning:
_refrobnicate_data_tables()
,_destroy_cache()
.
"Struct pointers" aren't entities that need a naming convention clause to cover them. They're just struct WhatEver *
. DON'T hide the fact that there is a pointer involved with a clever and "obvious" typedef. It serves no purpose, is longer to type, and destroys the balance between declaration and access.
You know, I like to keep it simple, but clear... So here's what I use, in C:
- Trivial Variables:
i,n,c
,etc... (Only one letter. If one letter isn'tclear, then make it a Local Variable) - Local Variables:
camelCase
- Global Variables:
g_camelCase
- Const Variables:
ALL_CAPS
- Pointer Variables: add a
p_
to the prefix. For global variables it would begp_var
, for local variablesp_var
, for const variablesp_VAR
. If far pointers are used then use anfp_
instead ofp_
. - Structs:
ModulePascalCase
(Module = full module name, or a 2-3 letter abbreviation, but still inPascalCase
.) - Struct Member Variables:
camelCase
- Enums:
ModulePascalCase
- Enum Values:
ALL_CAPS
- Public Functions:
ModulePascalCase
- Private Functions:
PascalCase
- Macros:
PascalCase
I typedef my structs, but use the same name forboth the tag and the typedef. The tag is not meant to be commonly used.Instead it's preferrable to use the typedef. I also forward declare the typedef in the public module header for encapsulation and so that I can use the typedef'd name in the definition.
Full struct
Example:
typdef struct UtilsExampleStruct UtilsExampleStruct;struct UtilsExampleStruct{ int var; UtilsExampleStruct *p_link;};