user714652
user714652

Reputation: 51

Suggestions for learning about macros in C

I have taken an undergrad course in programming Languages which covered C. However not that I have started working in a company in embedded systems, I see a plethora of macros being used regularly in C.

Please share some links from where I can learn more about macros.

I have K&R 2nd Ed, but I think their style is too terse. Something with more examples would be better for me.

Upvotes: 5

Views: 469

Answers (6)

Lindydancer
Lindydancer

Reputation: 26164

Here is a two-part tutorial on the C preprocessor called " Tips and tricks using the preprocesso" from IAR Systems:

Upvotes: 3

Chris
Chris

Reputation: 2060

Might be too obvious, but the wiki article on the C preprocessor is actually quite good and detailed:

http://en.wikipedia.org/wiki/C_preprocessor

Upvotes: 2

Heisenbug
Heisenbug

Reputation: 39194

Using macro is pretty simple:

#define MACRO_FUNCTION(par1, par2) (par1 * par2)
int product = MACRO_FUNCTION(4 ,5);

this is an example where MACRO_FUNCTION calculate product. Pay attention that macros are not type-checked. They are just substituted at compile time. So it's up to you use the right types .

Upvotes: 0

Tincu Gabi
Tincu Gabi

Reputation: 11

Hello,
As far as my knowledge goes the use of macro defs in embedded systems should 

be pretty scarce. That is to say, you should only use them for : constant definitions ( no magic number should appear in the code ), simple inline functions (for example ones that return a bool value), and that's pretty much it. Remember that even though inline functions save you some processor cycles , they make up by bloating code and preventing the debugging of said functions. Hope this helps and answers your question.

Upvotes: 0

paxdiablo
paxdiablo

Reputation: 882596

In all honesty, you should limit your use of macros to very simple definitions nowadays.

In other words, don't waste your time crafting complex functions with macros.

They tended to have three main uses in the past:

  • simple definitions for the pre-compiler to use such as #define USE_DEBUG and #ifdef USE_DEBUG. These are, by and large, stil very valuable in portable code.

  • fast "inline" functions such as #define SQR(x) ((x) * (x)) which are now much more suited to real inline functions. The macro version have a number of problems, one of which is that i = 7; j = SQR(i++); will not necessarily do what you expect.

  • pre-processor enumerations like #define OKAY 0, #define ERR_NOMEM 1 and so on - these are better done as real enumerations - because the macro versions are basic substitutions, you tend not to get the symbols in debugging information.

Upvotes: 5

BiGYaN
BiGYaN

Reputation: 7187

You can check out the following links:

Most of the tricks you'll have to pick up on your own. Maybe if you can post some of the macros you don't understand, we can help you out with those.

Upvotes: 2

Related Questions