C99的预处理器中的static_if [英] static_if in C99's preprocessor

查看:114
本文介绍了C99的预处理器中的static_if的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在C99中实现static_if?

Is it possible to implement static_if in C99?

#define STATIC_IF(COND, ...) \
     if (COND) MACRO1(__VA_ARGS__); \
     else MACRO2(__VA_ARGS__);

如何在这里正确实现STATIC_IF(…)?根据COND,参数应该传递给MACRO1MACRO2,但是两个宏的参数看起来都不同. COND是可静态测试的,类似于sizeof (…) > 42.

How can I properly implement STATIC_IF(…) in here? Depending on COND the arguments either should be passed to MACRO1 or MACRO2, but the arguments for both macros look differently. COND is statically testable, something like sizeof (…) > 42.

  • #if COND然后#define STATIC_IF MACRO1……在我的用例中不起作用.
  • 我不能使用特定于编译器的解决方案.
  • #if COND then #define STATIC_IF MACRO1 … wouldn't work for my use case.
  • I cannot use compiler specific solutions.

推荐答案

这是不可能的,因为对于预处理器来说,像sizeof(something)>42这样的条件不是静态的.预处理器是纯文本的(原则上,除算术运算).它不了解C或类型.

This is not possible, because a condition like sizeof(something)>42 is not static for the preprocessor. The preprocessor is purely textual (in principle, except for arithmetic). It does not know about C or types.

请注意,#if条件的表达式受到了严格限制.

Notice that expression of the condition in #if is severely constrained.

但是,您可以使用构建技巧.例如,您可能有一个独立的程序,例如

However, you could use build tricks. For instance, you might have a standalone program like

 // generate-sizeof.c
 #include <stdio.h>
 #include "foo-header.h"

 int main(int argc, char**argv) {
    const char* headername = NULL;
    if (argc<2) 
      { fprintf(stderr, "%s: missing header name\n", argv[0]); 
        exit(EXIT_FAILURE); };
    headername = argv[1]; 
    FILE *fh = fopen(headername, "w");
    if (!fh) { perror(headername); exit(EXIT_FAILURE); };
    fprintf(fp, "// generated file %s\n", headername);
    fprintf(fp, "#define SIZEOF_charptr %d\n", (int) sizeof(char*));
    fprintf(fp, "#define SIZEOF_Foo %d\n", (int) sizeof(Foo));
    fclose (fp);
 }

然后有一个类似

 generated-sizes.h : generate-sizeof foo-header.h
     ./generate-sizeof generated-sizes.h

在您的Makefile等中...

因此,您的构建机制将生成适当的标头.

So your build machinery will generate the appropriate headers.

如果您想交叉编译,事情会变得更加棘手!

然后您的标题中可能会包含#include "generated-sizes.h",以及更高版本的代码

Then you might have an #include "generated-sizes.h" in your header, and later code

#if SIZEOF_Foo > 42
#error cannot have such big Foo
#endif

这篇关于C99的预处理器中的static_if的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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