Electronic – Elegant structure for coding embedded systems in C

c18firmwarepic

Some questions regarding efficient coding style using C:

I'm working on 8-bit PIC controllers using C. I would like to know certain things about coding style and structure.

  1. I have read that keeping one header file is good programming style. But for segmenting functions rather easily for debugging and future development, can we keep more than 2 header files? Or, is it error prone? I trust creating header files and declaring function prototypes will remove the extern declaration in each related source files by doing so. (i.e. eeprom.h, data.h)

  2. Is it a good practice to keep all variables in a separate header file? Also, how do you deal with variables that are needed in more than one source file?

Best Answer

Regarding question 2: Variables are not supposed to be defined in a .h file. The purpose of a header file is to declare "public" functions and data structure used in a C file, so other C files know how to call/use them. By definition a header file will be included several times in a whole project, That's why .h files should not contain any code, or this code will be duplicated (actually, most of the time this causes a compilation error). The only case when a variable should be declared in a .h file is global variable shared across several C files, in that case the variable is defined in one of the C file and declared as extern in the .h file.

About global variables: The actual reason why global variables are not so good, is because it prevents code using it from being re-entrant. That means the code wont be compatible with recursivity nor multi-threading. On a 8 bit PIC with a ridiculously small stack, none of those techniques makes sense, so global variables are not so bad. It is however common practice to avoid global variables when you can, code is easier to read/debug/re-use that way.