philip yoo philip yoo - 24 days ago 7
C Question

Using a single define statement with include guards for function-like macros?

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:
http://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.

Answer

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.