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.
You are using only a single
VARvalue (the last one) because it can take only one value. If you want to mean different things byVARdepending on the context, you need to have source statements after each include.memorize.h: