在C中使用宏将项目追加到数组 [英] Append items to an array with a macro, in C

查看:81
本文介绍了在C中使用宏将项目追加到数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种应在编译时初始化的数组( C 语言).

I have an array (C language) that should be initialized at compile time.

例如:

DECLARE_CMD(f1, arg);
DECLARE_CMD(f2, arg);

从多个文件中调用DECLARE_CMD.

The DECLARE_CMD is called from multiple files.

我希望对此进行预处理.

I want this to be preprocessed in.

my_func_type my_funcs [] = {
   &f1,
   &f2
}

是否可以通过宏将项目附加到静态数组?

It is possible, with a macro, to append items to an static array?

我正在gcc4上使用C99(具有GNU扩展名).

I am using C99 (with GNU extensions) on gcc4.

推荐答案

注意::在您的问题中,每行结尾都有分号.这将严重干扰使用这些宏的任何尝试.因此,这取决于在哪里找到DECLARE_CMD(...)行以及如何找到DECLARE_CMD(...)行,以及是否可以解决分号问题.如果它们只是全部放在专用的头文件中,则可以执行以下操作:

NOTE: in your question there are semicolons at the end of every line. This will seriously interfere with any attempt to use these macros. So it depends on where and how the DECLARE_CMD(...) lines are found, and whether you can fix the semicolon problem. If they are simply in a dedicated header file all by themselves, you can do:

#define DECLARE_CMD(func, arg) &func,

my_func_type my_funcs [] {
    #include "file_with_declare_cmd.h"
};

...变成了

my_func_type my_funcs [] {
    &f1,
    &f2,
};

请阅读新的C:X宏,以对此进行详细说明.

Read The New C: X Macros for a good explanation of this.

如果您无法摆脱分号,它将被处理为:

If you can't get rid of the semicolons, this will be processed to:

my_func_type my_funcs [] {
    &f1,;
    &f2,;
};

...这显然是语法错误,因此将无法正常工作.

... which is obviously a syntax error, and so this won't work.

这篇关于在C中使用宏将项目追加到数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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