Where to create macros in C?

5

In terms of good programming practice, if I want to create a macro, for example, a macro that has more or less 30 lines of code, should I implement it in the file .c or .h ? What is good practice?

    
asked by anonymous 16.07.2015 / 16:01

2 answers

9

In terms of good practice you should do what is right for each situation. For this you need to gain experience. And there is nothing worse to gain experience than reading manuals that say what is right or wrong to do.

That said, macros should be avoided as much as possible. In current compilers they rarely need to be created. And if a macro has 30 lines there is certainly something wrong with it. Create a function and period.

Why the macro in place of the function? To have more performance? It might even make it worse. The compilers optimize the functions and they are "linearized" as would be the case with the macro if it is really feasible (and the compiler knows this better than the programmer in almost every situation), with numerous advantages over the macro.

But if you insist on error. In thesis nothing matters where you put it. Only the default is that you use files with .h extension to include in other files. And since the source of the macro must be available when the code that uses it is compiled, it is better to include a header file. Alias, this is another disadvantage of the macro.

In C ++ macros are not absolutely unnecessary. In C there are still some rare cases where they are interesting, but not to replace complex codes that should be in a function.

The SO has already been shown some macro problems .

    
16.07.2015 / 16:10
4

First point: avoid using macros as functions, do real functions.

Second point: In general, macros should be created in header files since they define identifiers to be used by external components.

But in your case I do not think this is what is intended. You just want to create an "inner" macro, which is not to be used by other code files that make use of your functions.

You can put the macro in an extension file ".c", or in a private extension file ".h".

#include "header.h"         // contem coisas publicas
#include "header-private.h" // contem coisas privadas

If you choose to solve real functions and you want to make them private ... do not set the prototype of these functions in the header file and define them with static

static int private_big_function(int x) { return x + 42; }
    
16.07.2015 / 16:56