1
votes

Is there a way to use only one define statement for this header, without changing the function-like macro into a function?

my.h file:

#ifndef MY_H
#define MY_H
#define MIN(x, y) ((x) > (y) ? (y) : (x))
#endif

For example, I was able to do the following for a constant:

pi.h file:

#ifndef PI
#define PI 3.14159
#endif

I also am aware of the warnings in regards to using function-like macros from posts like: https://stackoverflow.com/a/15575690/4803039

I just want to see if there is a more optimal/refactored way. It just seems weird to include an additional #define statement that defines the rest of the header body, when the header body only includes a #define statement itself.

2
Try still to define static inline functions instead of macros. And I am not sure that having such very small header files is sensible. I tend to favor having fewer, but bigger, header files, perhaps even only one header (see this about precompiling it)Basile Starynkevitch

2 Answers

5
votes

This is what you want:

#ifndef MIN
#define MIN(x, y) ((x) > (y) ? (y) : (x))
#endif
2
votes

Your approach would be fine - it's sufficient to guard against doubly defining macro. Adding a definition guard is usually useful if you want to protect an entire file. This serves to both shorten the code (as you don't have to guard each macro independently) and to make sure you have consistent definitions (e.g., if you want to make sure MIN and MAX are defined together). E.g.:

#ifndef MY_H
#define MY_H
#define MIN(x, y) ((x) > (y) ? (y) : (x))
#define MAX(x, y) ((x) < (y) ? (y) : (x))
#define PI 3.14159
#endif

If you just have a single macro/constant you want to define, you can guard it by its own definition, like @Danh suggested.