Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advantage of #define instead of creating a function in embedded

Tags:

c

embedded

Recently I got to view an embedded code in that they are using

#define print() printf("hello world")

instead of

void print() { printf("hello world"); }

My question what is the gain on using #define instead of creating a function?

like image 933
Joe Vince Avatar asked Nov 30 '22 14:11

Joe Vince


1 Answers

It may be related to performance.

A function call has some overhead (i.e. calling, saving things on the stack, returning, etc) while a macro is a direct substitution of the macro name with it's contents (i.e. no overhead).

In this example the functions foo and bar does exactly the same. foo uses a macro while bar uses a function call.

enter image description here

As you can see bar and printY together requires more instructions than foo .

So by using a macro the performance got a little better.

But... there are downsides to this approach:

  • Macros are hard to debug as you can't single step a macro

  • Extensive use of a macro increases the size of the binary (compared to using function call). Something that can impact performance in a negative direction.

Also notice that modern compilers (with optimization on) are really good at figuring out when it's a good idea to automatically inline a function (i.e. your code is written with a function call but the compiler decides to inline the function as if it was a macro). So you might get the same performance using function call.

Further, you can use the inline key word as a hint to the compiler that you think it will be good to inline a function. But even with that keyword the compiler may decide not to inline. The only way to make sure that the code gets inline, is by using a macro.

like image 171
Support Ukraine Avatar answered Dec 05 '22 07:12

Support Ukraine