2

Here is a macro I want to use, if X_DEFINED is defined it will be evaluated to DEFAULT_X otherwise it will be evaluated to x

#define GET_X(x) (defined(X_DEFINED) ? DEFAULT_X : x)

It doesn't compile, with the error

error: 'X_DEFINED' was not declared in this scope

Any suggestions? I want to be able to select between a parameter and a global variable based on if X_DEFINED was defined or not

2
  • 2
    suggestion: Let us know what you actually want to use this for so we can tell you how to do it without macros Commented May 8, 2019 at 15:16
  • btw this line alone does not produce any error. Please provide a minimal reproducible example Commented May 8, 2019 at 15:17

3 Answers 3

11

defined() only works in #if and similar preprocessor directives.

You want something like this:

#ifdef X_DEFINED
#define GET_X(x) DEFAULT_X
#else
#define GET_X(x) x
#endif
Sign up to request clarification or add additional context in comments.

1 Comment

Re: "defined() only works in #if" -- indeed. And the code could be written with #if defined(X_DEFINED) as well as with #ifdef X_DEFINED.
2

You need to define 2 different macros, depending on whether X_DEFINED is defined:

#ifdef X_DEFINED
#   define GET_X(x) x
#else
#   define GET_X(x) DEFAULT_X
#endif

Comments

1

Sloppy speaking you are mixing runtime stuff (evaluation of a ternary operator) with stuff that happens even before compilation (preprocessor). You can use #ifdef instead:

#ifdef X_DEFINED
    #define GET_X(x) DEFAULT_X
#else
    #define GET_X(x) x
#endif

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.