【问题标题】:Is there a way to write a macro that knows how many times another macro has been used?有没有办法编写一个知道另一个宏已经使用了多少次的宏?
【发布时间】:2014-02-21 11:08:20
【问题描述】:

我有以下类似的东西,但我不满意:

#define BEGIN {

#define END_1 };
#define END_2 END_1 };
#define END_3 END_2 };
// ... (possibly more of these) ...

#define END(x) END_ ## x

int main()
{
    BEGIN
    BEGIN
    BEGIN
    END(3) // <- I don't want to pass the 3 here

    BEGIN
    BEGIN
    END(2) // <- I don't want to pass the 2 here
}

我想重写BEGIN 和/或END 的定义,这样后者就不需要带参数了。

我相信这是不可能做到的,但我对 C 预处理器不是很有经验。至少有什么方法比我发布的示例更接近我的目标吗?

【问题讨论】:

  • 每次调用“BEGIN”时,也要调用i++,最后通过END(i)。只是一个建议。
  • @Abhineet:我真的不明白你的建议:(你能用一些编译代码说明你的意思吗?
  • 哇,认真的吗?您正在使用...宏...作为大括号...?

标签: c macros c-preprocessor


【解决方案1】:

GCC 和 MSVC 提供了一个非标准的 __COUNTER__ 宏,每次使用都会增加。但是,没有办法重置它。

无论您尝试什么,都应该以另一种方式完成。

【讨论】:

    【解决方案2】:

    以下内容可能会有所帮助: 它使用#include 而不是直接宏...

    开始.h:

    #if !defined(BEGIN_COUNT)
    # define BEGIN_COUNT 1
    #elif BEGIN_COUNT == 1
    # undef BEGIN_COUNT
    # define BEGIN_COUNT 2
    #elif BEGIN_COUNT == 2
    # undef BEGIN_COUNT
    # define BEGIN_COUNT 3
    // And so on
    #else
    # error "Hard coded limit reached for BEGIN_COUNT"
    #endif
    
    // The token to add:
    {
    

    end.h:

    #if !defined(BEGIN_COUNT)
    # error "unbalanced #include begin.h/end.h"
    #elif BEGIN_COUNT == 1
    // The token to add:
    }
    #elif BEGIN_COUNT == 2
    // The tokens to add:
    } }
    #elif BEGIN_COUNT == 3
    // The tokens to add:
    } } }
    #else
    # error "Hard coded limit reached for BEGIN_COUNT"
    #endif
    
    // reset counter
    # undef BEGIN_COUNT
    

    然后这样使用它:

    int main()
    {
        #include "begin.h"
        #include "begin.h"
    
        #include "end.h" // close the 2 'begin'
    
        #include "begin.h"
        #include "end.h" // close the last 'begin'
        return 0;
    }
    

    【讨论】:

      【解决方案3】:

      不,没有。 ???????

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-06-13
        • 2013-05-21
        • 2020-06-14
        • 2020-09-11
        • 2011-07-31
        相关资源
        最近更新 更多