简体   繁体   English

宏问题,带有多个语句

[英]Macro issue, with multiple statements

#define RUN_SOME_STUFF(...) {                                        \
            int x = 0;                                               \
            printf("[INFO] Do some stuff here ... %d\n", ++x);       \
            {__VA_ARGS__}                                            \
            printf("[INFO] end some stuff here\n");                  \
        }

How I'm using it: 我如何使用它:

...
RUN_SOME_STUFF(
{
    // middle:
    int y;
    y = 100;
    printf("Middle\n"); 
});
...

Now, I know that this is considered as a (very) ugly macro, but that's the main reason i'm asking for help. 现在,我知道这被认为是(非常)丑陋的宏,但这是我寻求帮助的主要原因。

The first problem with this is, if appears any type of error, the compiler will show the last line of the macro, as the incorrect line. 这样做的第一个问题是,如果出现任何类型的错误,则编译器将宏的最后一行显示为错误的行。 The printings are just examples to simplify the problem (in both code snippets), so there might be 20 line of complex, nested code, in which case that is very annoying. 印刷只是简化问题的示例(在两个代码片段中),因此可能会有20行复杂的嵌套代码,在这种情况下非常令人讨厌。

The second one is that the __LINE__ is resolved the same incorrect way 第二个问题是__LINE__以相同的错误方式解决

& I'm sure there are many more ... &我确定还有更多...

1. Are there any way to correct the above problems, so that the lines are correctly resolved? 1.有什么方法可以纠正上述问题,以便正确解决线路问题? (some sort of compilator option maybe?, I'm using VS2008/2010) (也许是某种编译器选项?我正在使用VS2008 / 2010)

2. If there's no way to make it with macro in a "cute" way, do I have any other options to do this? 2.如果没有办法以“可爱”的方式使用宏,是否还有其他选择可以做到这一点? Simply, I just want to run some code "around"(before and after) some other code. 简而言之,我只想在其他代码“前后”(前后)运行一些代码。

Edit: I would use this macro often, always with different "middle" content, so I can't write an inline function every time. 编辑:我经常会使用此宏,并且始终具有不同的“中间”内容,因此我不能每次都编写内联函数。

You can split the macro in two pieces. 您可以将宏分为两部分。 Not pretty, but it works when the macros are paired. 不是很漂亮,但是当宏配对时它可以工作。 Below both RUN_BEGIN; RUN_BEGIN;以下RUN_BEGIN; and RUN_END; RUN_END; are written so that they need a semicolon. 被编写为需要分号。

#define RUN_BEGIN \
    do { \
        int x = 0;   \
        printf("[INFO] Do some stuff here ... %d\n", ++x);  \
        {  \
            (void)0

#define RUN_END  \
        } \
        printf("[INFO] end some stuff here: %d\n",x ); \
    } while (0)

You probably would have better luck using function pointers . 使用函数指针可能会更好。 I haven't compiled this, but something like: 我还没有编译,但是类似:

void runSomeStuff(void (*stuff)(void))
{
    int x = 0;                                                   
    printf("[INFO] Do some stuff here ... %d\n", ++x);       
    (*stuff)();                                           
    printf("[INFO] end some stuff here\n");    
}

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

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