Macros on C, how to create useful Aliases for the Code

Macros on C, how to create useful Aliases for the Code

When any programmer deals with code that is large and complex, some simplification is required when dealing with multiple quantities of functions, variables and statements. With the help of macros on C, a pin or a constant value can be defined once and then reutilize it over and over. Need to do a modification of the value of the macro? Just change once and it is reflected immediately in the rest of the code. In other words, is a useful shortcut. In this short tutorial, check out how to implement this very useful feature.

Syntax of Macros

Macros consists in 3 parts. First, the word #define is placed in a new sentence. Afterwards, the label or name of it. Finally, the text is piece or argument to be replaced by the label.

#define label text

Example of Macros

Example 1: Constants

A common use for Macros is defining constants, such as math, frequency clocks, data, etc. For example:

#define clock 4000000

And it could be used this way:

int time=1/clock;

Example 2: Pins

Instead of using the pins of a microcontroller as they are named exactly, call them instead with the help of a Macro. If the main advantage is the simplicity, the secondary advantage is easiness to be reassigned in case the pin needs to change; the rest of the code is left unchanged! The following example is extracted from a tutorial about How to drive 7-Segment Displays with a 8-bit PIC.

//Macros for the 7-segment display
#define f PORTAbits.RA2
#define g PORTCbits.RC0
#define a PORTCbits.RC1
#define b PORTCbits.RC2
#define e PORTCbits.RC3
#define d PORTCbits.RC4
#define c PORTCbits.RC5

To use this shortcut, just call it by the label.

f=1;

Resources

  • Macros. MPLab Developer Help. Link.

techZorro's Index of Content

Keep Reading!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.