C Programming

Overview

This is the main parent page for C programming. The information in the following child pages is mostly geared towards C programming in an embedded environment, although there are some parts dedicated to programming on Linux and other environments.

Child Pages

.bss Section
Info on the .bss section which is part of a compiled object file.
Arithmetic Operators
Info on the arithmetic operators in C (plus, minus, multiply, divide, modulus, increment, decrement, bit-shift, e.t.c).
Arrays
Single dimension arrays, multidimensional arrays, passing arrays into functions, ragged arrays, code examples and more info about using arrays in C.
Assertions (assert())
An overview, macros, code examples, external links, and more information on assertions (assert()) in the C programming language.
Bit Fields And Bit Manipulation/Masking
Overview, masking, setting/clearing bits, macros, industry uses and more info about bit fields, a common programming construct, especially in firmware.
C Naming Conventions
My preferred C naming conventions, including how to name variables (both local and global), functions and how to deal with acronyms.
C Related File Extensions
What do the different file extensions used during a C build process represent?
Comma Operator
What the comma operator in C actually is (note we are not talking about the comma used to separate variables passed into a function), it's precedence, when is should be used (very infrequently), and when it shouldn't (i.e. most of the time)
Commenting And Documentation
ContentsGeneral TipsC Supports URL’s, Wait What?Commenting StylesDoxygenGeneral Tips Always use  \\ style comments where possible. This allows you to use /* style comments for commenting out large blocks of code when debugging. If you want to comment a block of code which has /* comments inside it, you will run into problems! (unfortunately, */ style comments don’t nest in … Continue reading Commenting And Documentation
Common C Compile/Build Errors
ContentsOverview“pointer of type void used in arithmetic”“elf section ‘.bss’ will not fit in region ‘ram’“Suggested parenthesis around assignment used as a truth value”“Subscripted value is neither array nor pointer”“#pragma once in main file”“variable or field declared void”“macro names must be identifiers”“Not In Formal Parameter List”double free or corruptionOverview These C compile/build errors and warnings are … Continue reading Common C Compile/Build Errors
Control Statements
Control statements in the C programming language are constructs which allow you to conditionally execute pieces of code, based on whether a condition is true or false.
Data Type Promotions
C if (-1 < (unsigned char)1) printf("less than"); else printf("NOT less than"); // Prints "less than" if (-1 < (unsigned int)1) printf("less than"); else printf("NOT less than"); // Prints "not less than"!!! 12345678910111213 if (-1 < (unsigned char)1) printf("less than");else         printf("NOT less than");  // Prints "less than" if (-1 < (unsigned int)1) printf("less than");else         printf("NOT less … Continue reading Data Type Promotions
Data Types
Information on the standard data types available in C, and how to write portable code.
Dynamic Memory Allocation
ContentsOverviewThread-Safetymalloc()realloc()alloca()Appending An Element To An ArrayOverview Dynamic memory allocation is the process of assigning space for variables at run time. This is done automatically for function-scope variables which are put onto the stack when they are defined, but dynamic memory allocation usually refers to the process of using one of the malloc-family functions to manually … Continue reading Dynamic Memory Allocation
Enumerations
ContentsOverviewUsefullnessSyntaxInterchangeabilityOptimisationThe Data Type Of An Enum Overview Enumerations in C are in their most basic sense, a way of creating a meaningful word-based list type. Enumerations are an alternative to using C preprocessor macros to create words which represent numbers. For example: Using Preprocessor Macros Instead Of Enums C #define RED 0 #define GREEN 1 … Continue reading Enumerations
File Input And Output
Contentsfopen()The standard C library provides functions for writing input and output to files. Most of the file input/output functions are declared in header stdio.h. Add the line #include <stdio.h> to your source code to use file I/O functions. fopen() fopen() is used to open a file. The function declaration changed in C99, by adding the keyword restrict. … Continue reading File Input And Output
Header Guards
Code examples and comparisons on how to implement header guards in C code using either the #ifndef, #pragma once, or #import method.
Inserting Assembly Code Into C
ContentsOverviewThe Volatile KeywordAn ExampleOverview Assembly code can be inserted into C code. This is usually done when you want to optimise something for a particular architecture (assembly is NOT as portable as C). There are two types, “basic inline” assembly, and “extended” assembly. If you are using the GCC compiler, you can insert assembly code … Continue reading Inserting Assembly Code Into C
Linkage
ContentsThe extern KeywordThe extern Keyword The extern  keyword is a linkage modifier that has different meanings in different contexts. In C++, when used it the form extern "C", it can be used to declare functions and variables which should have C linkage. extern is not normally used in function definitions/declarations. With variables, extern is normally used … Continue reading Linkage
Linux Bash Commands For C
Below are a list of the most essential bash commands when working with the c programming language in linux. Examples tested on Ubuntu v12.04. # Install GNU C compiler and other essential C programs onto Linux platform sudo apt-get install build-essential # Creates c file called main.c in current directory and opens gedit to begin … Continue reading Linux Bash Commands For C
Linux Serial Ports Using C
ContentsOverviewVMIN and VTIME ExplainedIssues With GettyExampleOverview Unluckily, using serial ports in Linux is not the easiest thing in the world. When dealing with the termios.h header, there are many finicky settings buried within multiple bytes worth of bitfields. VMIN and VTIME Explained VMIN and VTIME are a source of confusion for many programmers when trying to configure a … Continue reading Linux Serial Ports Using C
Local Jumps (goto)
ContentsOverviewC Supports URL’s, Wait What?Overview The label operator ( 🙂 and  goto statement in C allows you to perform local jumps. A local jump is a jump in code execution within the same function. This is opposed to non-local jumps, which can jump between functions ( setjmp() and longjmp()). The reason jumps are split into … Continue reading Local Jumps (goto)
Logical Operators
ContentsC Logical Operators Cheat SheetThe Conditional Operator (?:)Logical Short-Circuit EvaluationWhy Is There No Logical Exclusive OR (^^)?Conditional OperatorC Logical Operators Cheat Sheet Symbol Name Description Bit-wise & Bit-wise AND Operator   | Bit-wise Non-exclusive OR (otherwise just known as Bit-wise OR)   ^ Bit-wise Exclusive OR Do not think this sign is the mathematical sign … Continue reading Logical Operators
Non-local Jumps (setjmp(), longjmp())
ContentsOverviewDefinitionsWhat Do I Need To Include?Making Your Own Exception Handlers In CA Word Of Caution To C++ UsersOverview The C functions setjmp() and longjmp() provide the ability to perform non-local jumps. A non-local jump is a jump in code execution between two seperate functions. This is opposed the the local jump, goto which can perform … Continue reading Non-local Jumps (setjmp(), longjmp())
Object-Orientated C
ContentsOverviewThe Basic ObjectMethodsWait, What About A Constructor?PolymorphismInterfacing To Imperative CodeOverview Although C is not generally thought of as an object-orientated language, it’s flexibility does allow object-orientated style code to be written, albeit with slightly more verbose syntax than a “object-orientated” language such as C++. Object-orientated code is a broad term for a number of different coding ideas. … Continue reading Object-Orientated C
Pointers
Excerpt testing!
Portability
Use data types defined in stdint.h for better portability. These include: C int8_t uint8_t int16_t uint16_t int32_t uint32_t int64_t uint64_t // Not all compilers/platforms (especially microcontroller ones) support these last two int128_t uint128_t 1234567891011 int8_tuint8_tint16_tuint16_tint32_tuint32_tint64_tuint64_t// Not all compilers/platforms (especially microcontroller ones) support these last twoint128_tuint128_t This is because the data types such as int can … Continue reading Portability
Preprocessor
Variable-style macros, function-style macros, variadic macros, stringification, conditional statements (#if, #else), #include, #warning, #error and more info about the C preprocessor.
Processing Command-Line Input
ContentsOverviewFirst, A Little Terminologygetopt()Examplegetopt_long()ExampleSimilar FunctionsOverview This page concerns itself largely on the GNU implementation of getopt() and it’s variants (more likely than not you will be using this library), and how they relate to the POSIX standard. First, A Little Terminology Name Description Example Command-line A text-based program (called a terminal) that is used to call … Continue reading Processing Command-Line Input
Reading User Input
ContentsOverviewUsing scanf()Overview Reading user input is the process of prompting the user for input, and then receiving this by the software so that actions can be done based on what was typed. This applies more to C programs running on Linux and other terminal-capable architectures, rather than embedded microcontrollers. Using scanf() scanf()  is one of the … Continue reading Reading User Input
Reducing Code Execution Time
ContentsMultiplication And DivisionPowers And Square RootsFixed PointTrigonometryMultiplication And Division Fixed multiplication and division can converted to bit shifting to optimise code. The bit shifting operations can be found by doing a Taylor’s expansion of the equation. The error in the result depends on how many bit shifting operations you wish to perform. The below example … Continue reading Reducing Code Execution Time
Standards And Versions
ContentsC99C99 C99 is an informal name for ISO/IEC 9899:1999. Compiling the the flag -std=c99 gives asm() not defined errors, however compiling with -std=gnu99 instead fixes this. Like this:Like Loading...
String Manipulation
ContentsASCII CharactersNull CharacterCarriage Return And New LineCase SwitchingThe Standard LibrariesStringsSpecial CharactersCopyingNumber To String Manipulationatof()strtod()Decoding/Encoding Stringsprintf (And It’s Variants)printf()Conversion SpecifiersFormat SpecifiersPortable size_t Printingsnprintf()ASCII Characters Null Character The null character (represented by '\0' , 0x00 , or a constant defined as NULL ) is used to terminate strings and arrays (essentially the same thing anyway). Most string-based commands will automatically … Continue reading String Manipulation
Structures
ContentsOverviewInitialising StructuresManipulating StructuresSelf-referencing StructuresOverview Structures can be used to do a “object-orientated” style of programming in C, a language which was originally designed to be functional. Initialising Structures Initialising structures is way of defining what the values of the variables inside the struct will be at the time of creation. Note that there is a … Continue reading Structures
Switch Statements
ContentsFall-throughSwitch Statement EfficiencyEnclosing {} Braces Fall-through Fall-through occurs when the previous case had no break statement (or other statement which could cause the program counter to change, e.g. goto, return). It is considered to be one of the biggest design errors of the C programming language, but unfortunately due to existing code relying on fall-through to … Continue reading Switch Statements
System Calls
ContentsStandard C System Calls_exit()close()Most standard C libraries depend on a number of subroutine calls for interacting with system services. These are called system calls. Standard C System Calls _exit() Exits a program without cleaning up files. close() Closes a file Minimal Implementation Of close() C int close(int file) { return -1; } 123 int close(int … Continue reading System Calls
Tips And Tricks
ContentsPlace A Statically Determinable Upper-Bound On All LoopsPlace A Statically Determinable Upper-Bound On All Loops Having a statically determinable upper-bound on all loops creates a directed acyclic call graph of your program. This can help static-analysis tools determine the upper-limits of stack/memory usage. The exceptions to this rule include: The main-event loop of a task. … Continue reading Tips And Tricks
Variadic Functions
ContentsOverviewSyntaxOverview Variadic functions are functions which can take in a variable number of arguments. The C language by itself provides no special syntax for dealing with them, but variadic functions are supported by the standard C library ( <varargs.h>). Syntax A variadic function is declared as: Variadic Function Definition C MyFunction(uint32_t arg1, ...); 1 MyFunction(uint32_t … Continue reading Variadic Functions

Endless Loops

Endless loops are usually used in embedded programming for the main function. They are used to keep the code running continuously, since exiting the main function from most embedded systems is undefined (and why would you want to?). In a non-scheduler based environment (i.e., no operating system), it is commonly called the “main loop”. The only code not placed inside (or called from) the main loop is the initialisation code and interrupt handlers. Two common ways of making an endless loop are:

In an embedded operating system based environment, there may be more than one endless loop. Typically, there is one per concurrent task or process (such as with FreeRTOS). An interrupt driven scheduler controls which loop the processor is currently executing by changing the CPU’s instruction pointer.

Unions

Unions are used to create a data structure that can be addressed using different data types. For example, you can create a 2 byte slot in memory that can be addresses as one 16-bit piece of data or two 8-bit pieces. An example of a union is shown below.

The Standard Libraries

Library Name Description Popular Objects In Library Comments
<stdio.h> Contains functions for input/output data streams printf(), sprintf(), scanf() Very common header file. You be searching hard to find a C project which didn’t use this library.
<stdlib.h>   atoi(), atof(), rand(), malloc(), abs(), div(), NULL Contains a mixture of different functions, some mathematically based, while others related to memory management.
<stdbool.h> Contains definitions for true and false true, false Added in C99, contains macros for true and false. C++ supports these natively.
<math.h> Contains mathematical functions sin(), cos(), tan(), pow(), sqrt(), exp(), log, ceil(), floor() Software based operations. These can be computationally expensive!

Function Scope

Functions inside a .c file can only be called within the same file unless one of the following is done:

  • The function declaration is put in the associated .h file (rather than in the .c file). This header file is then included in other .c files that want to access this functions
  • A pointer to the function is passed to an external function via another global function in the same .c file
  • The function is declared in another .c file with the qualifier ‘extern’

Variable Scope

Variables declared within a .c file (a ‘module’), but not within a function are by default, are ‘external’. To make the variable visible only to the module it is in, put the keyword ‘static’ infront of the indentifier. Do not put the word static infront of variables declared in a .h file, as you may get compiler warnings/errors such as ‘unused variable present’, even though you may be using it.

Coding Standards

The Joint Strike Fighter C++ Coding Standards (semi-applicable to C also). Created by Lockhead Martin. A bit of a hefty read (I would never read this cover-to-cover unless I had too), but there is some good stuff in there.

There are programs out there which format and tidy up your code. One such example is AStyle (or Artistic Stylle), a open-source program which is a

…source code indenter, formatter, and beautifier for the C, C++, C# and Java programming languages

Click here to visit their website.

Reducing Code Size

  • Replace the standard sprintf() function with a optimised or ‘lite’ version which can save a huge amount of code space! At the same time start using a snprintf() version with the sizeof() function, which is safer (prevents most causes of buffer overruns from occuring).A smaller version of the printf function family can be found here (tinyprintf).
  • Reducing buffer sizes to remove excess allocated space. Normally, you can get away with reducing the buffer sizes you allocated when first writing the code. Be careful not to cause buffer overruns though! Use safe string functions (e.g. snprintf()) combined with the sizeof() command whenever possible!

.C (C Code) Files

  • Never include .c files! If you do, you may get redefinition errors from the linker.

.H (Header) Files

Header files are ‘copy-paste’ files in which their contents get dumped into the top of any C file that includes them, and then the C file compiled. The compiler recognises a header file when it has a “.h” extension. Only objects that you want to make accessable from other .c files should go in a .h file (aka the interface). Everything else should be defined in the .c file. In a header file you should have:

  • A header guard (either the #ifndef or #pragma once style)
  • Declarations (aka prototypes) of variables and functions that you want to make global
  • Preprocessor macro definitions used across many .c files
  • Public function declarations
  • Public typedef declarations (of structs and enums)
  • Public variables (although it can be good practise to get rid of all public variables and instead provide public functions to access them)

FreeRTOS

FreeRTOS is a real-time operating system written in C and designed for embedded platforms. It uses blocks of code called ‘tasks’ and a ‘scheduler’ which allocates a certain amount of processing ability to each task. FreeRTOS uses queue’s to pass information between tasks, and both semiphores and mutexs for controlling the sharing of resources (such as a UART peripheral). It also has additional plug-ins (which you may or may not have to buy a license to use commercially)

  • FreeRTOS CLI (Command-line Interface) – Allows you to easily create a command-line style interface with an embedded platform allowing you to send it commands and parameters, as well as receiving back results. It is written generically so can be connected to any standard embedded communication interface (such as a UART, SPI, I2C e.t.c).

External Links

The C library reference (http://www.cplusplus.com/reference/clibrary/) provides good explanations on standard functions that are included with the C programming language, organised by file and then by function. Also check out the GNU C Pre-processor reference.

Link Title Reference
The GNU C Library Reference Manual The GNU C Library Reference Manual www.gnu.org
C Reference Card (ANSI) v2.2 C Reference Guide (ANSI) v2.2 http://www.digilife.be/quickreferences/QRC /C%20Reference%20Card%20%28ANSI%29%202.2.pdf