= Starlink C Programming =

The Starlink software is mainly in Fortran but we are now writing new code in C to help with multi-threading goals. This page contains general C programming style guides and Starlink-specific instructions using new facilities added directly for the C programmer.

== General C tips ==

 * Do not use malloc/free directly. See below.

 * Never cast the return value of a malloc type routine since void* does not need type casting

 * When determining how many bytes to malloc do not use sizeof(int) or sizeof(double) or whatever, use sizeof(*var). This way if you have declared something as  "int *x" and then decide it should be a "long *x" you do not have to remember to fix all the sizeof(int) lines, since sizeof(*x) will already be correct.

 * Do not use global variables if at all possible. Makes threading impossible.

 * Make use of structs and typedef

 * Turn on as many compiler warnings as you can (-Wall -Wextra at the very least) and '''listen''' to them. They are there to help.

 * Never use sprintf. Always use snprintf and check the return value.

== Starlink C tips ==

 * If you have an AST dependency in your library/application use astMalloc/astFree/astGrow for memory management

 * If you do not have an AST dependendency use starMalloc/starFree

 * The MERS routines have sprintf formatting so use of message tokens is rarely necessary. msgOutiff, ersRepf and others let you embed formatting directly.

 * If you need access to a fortran library put the C wrapper in the library itself rather than locally in your application. Then other people can benefit.

 * The ONE library gives a number of helper routines specifically to allow use of C library routines with Starlink status: one_snprintf, one_strlcpy, one_strlcat and one_strtod. Use them. Also one_wordexp_noglob for shell expansion.