mariner
mariner

Reputation: 930

C Macro - was not declared in this scope error

#define SET_NONEMPTY(x) { const NString& var = r->hdrs->get_##x(); \
  if (!var.empty()) { \
    set_##x_for_serving(r->request, var.data(), var.length()); \
  } \
}

The above macro tries to set a request member if it is not empty, but I get this following error: 'set_x_for_serving' was not declared in this scope while I use this macro.

What is wrong in the above macro?

Upvotes: 7

Views: 3286

Answers (2)

Brian Cain
Brian Cain

Reputation: 14619

You need the token-pasting operator on both sides of x in order to get it to substitute correctly.

#define SET_NONEMPTY(x) { const NString& var = r->hdrs->get_##x(); \
  if (!var.empty()) { \
    set_##x##_for_serving(r->request, var.data(), var.length()); \
  } \
}

Upvotes: 9

abelenky
abelenky

Reputation: 64730

It looks like inside a macro call of SET_NONEMPTY(foobar), you expect that set_##x_for_serving will expand to set_foobar_for_serving.

Is that correct?

If so, the phrase x_for_serving is a single token and the x will not be seen by the preprocessor as an item to replace.

I think you want set_##x##_for_serving instead:

#define SET_NONEMPTY(x) { const NString& var = r->hdrs->get_##x(); \
  if (!var.empty()) {                                              \
    set_##x##_for_serving(r->request, var.data(), var.length());   \
  }                                                                \
}

Upvotes: 5

Related Questions