philip yoo
philip yoo

Reputation: 2522

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

Upvotes: 2

Views: 408

Answers (2)

Mureinik
Mureinik

Reputation: 311563

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.

Upvotes: 3

Danh
Danh

Reputation: 6016

This is what you want:

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

Upvotes: 6

Related Questions