C++ Macro with Memory

旧时模样 提交于 2019-12-13 13:42:52

问题


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.


回答1:


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)



回答2:


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.




回答3:


You need to move the #undef MEMORIZE line -- take it out of memorize.h and put it right before #define MEMORIZE everywhere that appears.



来源:https://stackoverflow.com/questions/9526096/c-macro-with-memory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!