Reputation: 1224
This is originally posted as an answer to c++ macros with memory?
But somehow I am not able to get this compiled. I might be missing something here. (I have a feeling that this is something C++ can do)
main.cpp
#include <iostream>
using namespace std;
const char * hello = "hello";
const char * world = "world";
#define VAR
#define MEMORIZE world
#include "memorize.h"
#define MEMORIZE hello
#include "memorize.h"
int main() {
cout << VAR << endl;
return 0;
}
memorize.h
#undef VAR
#ifndef MEMORIZE
# error "No Argument to memorize.h"
#endif
#define VAR MEMORIZE
#undef MEMORIZE
The compile error that I am getting is this:
[100%] Building CXX object CMakeFiles/main.dir/main.cpp.o
error: use of undeclared identifier 'MEMORIZE'
cout << VAR << endl;
^
note: instantiated from:
#define VAR MEMORIZE
^
1 error generated.
make[2]: *** [CMakeFiles/main.dir/main.cpp.o] Error 1
make[1]: *** [CMakeFiles/main.dir/all] Error 2
make: *** [all] Error 2
I really want to get this memory thing to work in preprocessing phase. Can someone help? I think BOOST_PP_COUNTER
in 1.49
also uses this technique but i couldn't figure out how.
Upvotes: 4
Views: 450
Reputation: 126418
You need to move the #undef MEMORIZE
line -- take it out of memorize.h and put it right before #define MEMORIZE
everywhere that appears.
Upvotes: 0
Reputation: 98088
You are using only a single VAR
value (the last one) because it can take only one value. If you want to mean different things by VAR
depending on the context, you need to have source statements after each include.
#define xstr(a) str(a)
#define str(a) #a
int main() {
#define MEMORIZE world
#include "memorize.h"
cout << VAR << endl;
#undef MEMORIZE
#define MEMORIZE hello
#include "memorize.h"
cout << VAR << endl;
return 0;
}
memorize.h:
#undef VAR
#ifndef MEMORIZE
# error "No Argument to memorize.h"
#endif
#define VAR xstr(MEMORIZE)
Upvotes: 1
Reputation: 44374
You are are setting the VAR
macro to the token MEMORIZE
, which you are promptly undefining. The line:
cout << VAR << endl;
ends up as:
cout << MEMORIZE << endl;
and since MEMORIZE
is undeclared, you get the error. It thinks MEMORIZE
is a variable name.
Upvotes: 0