Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Macro - was not declared in this scope error

Tags:

c

macros

#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?

like image 340
mariner Avatar asked Oct 07 '13 13:10

mariner


People also ask

How do I fix error not declared in this scope?

To resolve this error, a first method that is helpful would be declaring the function prototype before the main() method. So, we have used the function prototype before the main method in the updated code. When we have compiled the code, it throws no exceptions and runs properly.

What is not declared in this scope in C?

“not declared in this scope” means the variable you referenced isn't defined. The action you should likely take is as follows: You should carefully look at the variable, method or function name you referenced and see if you made a typo.


2 Answers

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()); \
  } \
}
like image 188
Brian Cain Avatar answered Sep 21 '22 14:09

Brian Cain


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());   \
  }                                                                \
}
like image 22
abelenky Avatar answered Sep 21 '22 14:09

abelenky