Skip to the content of the web site.

Macros: #define

In C and C++, the #define can be used to declare a macro within the scope of a file. A macro substitution in C and C++ occurs prior to the compiler during the exeuction of the preprocessor.

Macros are identified by symbols, and by convention, although not necessarily, they are written using all capital letters.

Symbol substitution

The easiest form of a macro is a direct substitution:

#define SYMBOL whatever you please...

Whevever the preprocesor finds the symbol SYMBOL in the file, it substitutes it with whatever you please.... Because the proprocessor is not part of the compiler, the #define statement does not require a semicolon to end it. Instead, the macro will replace everything up to the end of the line.

Function macro

If the character immediately following the macro symbol is an opening parenthesis, this defines a function macro:

#define SQR(x) ((x)+(x))

The arguments to a macro are similar to that of a function; however, the substitution is done blindly. Consequently, if the above were defined as

#define SQR(x) x*x

then int z = y/SQR(x + 1); would be rendered as

          int z = y/x + 1*x + 1;

while what is desired is

          int z = y/((x + 1)*(x + 1));

You will note that even leaving the surrounding parentheses would render the substitution invalid: one would have int z = y / (x + 1) * (x + 1);, which would be interpreted as (y/(x + 1))*(x + 1).

Common macros are:

#define MAX(x, y) ((x) >= (y)?(x):(y))

and

#define BIT(n) (1 << (n))

The arguments to a macro are similar to that of a function; however, the substitution is done blindly.

Often macros are used for casting

 #define U32_BE(v)      (U32)(__rev(v))
 #define U16_BE(v)      (U16)(__rev(v) >> 16)
 #define U32_LE(v)      (U32)(v)
 #define U16_LE(v)      (U16)(v)

or for creating alternate definitions of functions functions. In this case, task 0 is identified as self:

#define os_tsk_delete_self()          os_tsk_delete(0)
#define os_tsk_prio_self(prio)        os_tsk_prio(0,prio)

Macros longer than a line

A macro will be extended to multiple lines if the lines are terminated by a backslash \, as shown here:

#define os_sys_init_user(tsk,prio,stk,size)                                 \
                                      os_sys_init0(tsk,prio|(size<<8),stk)