Variables
- Variables should be named in lower snake case. ie. `this_is_a_variable`.
- Absolutely no exposing of global variables. All components should implement accessor methods, if applicable.
- Variables in c files should be declared as static if they are outside the scope of any function. This ensures that the variable scope is contained within that file, and tells the developer that the variable isnt used anywher else.
Example
/** * @file SomeFile.c * @author The Grinch * @date March 5, 2012 */ //BAD int someGlobalVariable = 0; //GOOD static int16_t some_nice_variable = 0;
Static variables
Note that in most cases, you're NOT going to want to declare a variable as static if inside a function
Functions
- Camel case on all functions. Eg. helloWorld()
Example
//BAD
void some_bad_function();
void someworsefunction();
void WhatIsThisAbomonation();
//GOOD
void goodFunctionName();
Constants, Enums, Defines
- Capital snake case on all constants, #defines, and enumerations
- Typedef enums
- Defines that are only used in a single c file, and aren't meant to be modified by the developer should be placed in the .c file, not the .h file
Example
#define HELLO_WORLD 4
Structs
- If structs are to be exposed in an interface (in a .h file) typedef it
- Raw struct names (in the initial declaration) should be the same as the typedef name
- Field variables that are not meant to be accessed by other modules should begin with an underscore
- Naming for structs should be capital camel case
Example
//BAD
struct helloworld{
int do_not_modify;
} HelloWorld;
//good
typedef struct HelloWorld{
int16_t _do_not_modify;
uint32_t can_access_directly;
} HelloWorld;
Types
For code portability and easier unit testing, please use the types defined in <stdint.h> and <stdbool.h>. The table below summarizes the different possible types and their conversion to the standard types. As you can see, it also saves on a lot of typing.
C Standard Type | Length in Bytes (XC16) | Portable Type |
---|---|---|
char | 1 | int8_t |
unsigned char | 1 | uint8_t |
int | 2 | int16_t |
unsigned int | 2 | uint16_t |
long int | 4 | int32_t |
long unsigned int | 4 | uint32_t |
long long int | 8 | int64_t |
unsigned long long int | 8 | uint64_t |
float | 4 | -- |
double | 8 | -- |
long double | 8 | -- |
-- | 1 | bool |
Booleans
Note that with the inclusion of <stdbool.h>, you get the true and false types available to use
Doubles vs Long Doubles
On most systems, a long double guarantees 8 bytes. Even though with XC16 they are the same, it is highly recommended to use long doubles over doubles.
Add Comment