简体   繁体   English

在宏函数C ++中设置宏变量值

[英]Setting macro-variable-value in macro-function C++

I need to call a function which call a macro-function to change macro-value in runtime. 我需要调用一个函数,该函数调用宏函数以在运行时更改宏值。

This code isn't compiled: 此代码未编译:

#define MY_MACRO 32
#define SET_MY_MACRO_VAL(IS_TRUE)(MY_MACRO=(IS_TRUE)?16:U32)

In function SET_MY_MACRO_VAL 在功能SET_MY_MACRO_VAL

> error: lvalue required as left operand of assignment

    #define SET_MY_MACRO_VAL(IS_TRUE)(MY_MACRO=(IS_TRUE)?16:U32)
                                          ^
    in expansion of macro 'SET_MY_MACRO_VAL'
         SET_MY_MACRO_VAL(True);
         ^

Macro value are replaced BEFORE compile time by the preprocessor and do not exist at run time. 宏值在编译之前被预处理器替换,并且在运行时不存在。

It is not a variable it is simply a way of using text for the value "32". 它不是变量,它只是使用文本作为值“ 32”的一种方式。

If you do this : 如果您这样做:

#define MY_MACRO 32
#define SET_MY_MACRO_VAL(IS_TRUE)(MY_MACRO=(IS_TRUE)?16:U32)

It will be expanded to this 它将扩展到这个

#define MY_MACRO 32
#define SET_MY_MACRO_VAL(IS_TRUE)(32=(IS_TRUE)?16:U32)

What you can do is use a #define 您可以使用#define

#ifdef SET_MACRO_VAL_32
#define MY_MACRO 32
#else
#define MY_MACRO 16
#endif

Or use a conditionnal macro if you prefer 或使用条件宏

#if (IS_TRUE>0)
#define MY_MACRO 32
#else
#define MY_MACRO 16
#endif

Edit : In C++, you shouldn't really need macro though. 编辑:在C ++中,虽然您实际上不需要宏。 You can use template and / or constexpr variable for compile-time value. 您可以使用模板和/或constexpr变量作为编译时值。 In C++17 you can even use constexpr if . 在C ++ 17中,如果甚至可以使用constexpr if

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM