伯爵用C preprocessor ​​2 code地点之间的线 [英] Count lines between two code locations in C preprocessor

查看:116
本文介绍了伯爵用C preprocessor ​​2 code地点之间的线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用C preprocessor来,计算两个code地点之间线路的数量。其基本思路是这样的:

I want to use the C preprocessor to count the amount of lines between two code locations. The basic idea is something like this:

#define START __LINE__
static char* string_list[] = {
    "some string",
    "another string",
    ...
    "last string"
};
#define END __LINE__
#if END - START > 42
    #error Too many entries
#endif

当然,这并不在这种情况下,因为工作开始 END 仅仅是<$的重定义C $ C> __ __ LINE 宏。结果
我被玩弄的 ## 运营商了一点,但我不能得到preprocessor评估开始结束preprocessor运行时

Of course this doesn't work because in this case START and END are merely redefinitions of the __LINE__ macro.
I was playing around a bit with the # and ## operators, but I could not get the preprocessor to evaluate START and END while the preprocessor is running.

我的问题是:这是可能在所有

My question is: is this possible at all?

检查运行期间,阵列的大小是不是一种选择。结果,
感谢提前任何提示或想法!

Checking the size of the array during runtime is not an option.
Thanks for any hints or ideas in advance!

推荐答案

您不应该使用这些宏用于此目的:如果你的地方引入一个额外的行code会变得完全不可维护。而如果有太多的几行?

You shouldn't use those macros for that purpose: the code will become completely unmaintainable if you introduce an extra line somewhere. And what if there are too few lines?

代替宏,使用静态断言:

Instead of macros, use a static assert:

static_assert(sizeof(string_list) / sizeof(*string_list) == SOME_CONSTANT,
               "Wrong number of entries in string list.");

如果你不使用它C11有static_assert的支持,你可以写这样的自信心,比如像这样的:

If you aren't using C11 which has support for static_assert, you can write such an assert yourself, for example like this:

#define COMPILE_TIME_ASSERT(expr) {typedef uint8_t COMP_TIME_ASSERT[(expr) ? 1 : 0];}

这篇关于伯爵用C preprocessor ​​2 code地点之间的线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆