可选的初始化程序,通过预处理器技巧?
我知道这行不通,但希望你能看到我正在尝试做的事情
#if ASSIGN_ALLOWED
#define MAYBE_SKIP_REST_OF_LINE
#else
#define MAYBE_SKIP_REST_OF_LINE ; //
#endif
char str[80] MAYBE_SKIP_REST_OF_LINE = "Hello\n";
long array[3] MAYBE_SKIP_REST_OF_LINE = { 7,8,9 };
int x MAYBE_SKIP_REST_OF_LINE = 3;
//...many many more similar lines...
有没有办法做到这一点,使其有效?
I know that this will not work, but hopefully you can see what I'm trying to do
#if ASSIGN_ALLOWED
#define MAYBE_SKIP_REST_OF_LINE
#else
#define MAYBE_SKIP_REST_OF_LINE ; //
#endif
char str[80] MAYBE_SKIP_REST_OF_LINE = "Hello\n";
long array[3] MAYBE_SKIP_REST_OF_LINE = { 7,8,9 };
int x MAYBE_SKIP_REST_OF_LINE = 3;
//...many many more similar lines...
Is there a way to do this such that it works?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
当然:
任何包含逗号的初始化程序(例如示例中的
array
)都需要从其自己的宏进行扩展,例如上面的ARRAY_INIT
。如果您的编译器支持 C99 可变参数宏,那么您可以以更简洁的方式进行操作:Sure:
Any initialisers containing commas, like for
array
in the example, will need to be expanded from their own macro, likeARRAY_INIT
in the above. If your compiler supports C99 varargs macros, then you can instead do it in a cleaner way:由于注释在预处理器运行中被过滤掉,我不这么认为
As comments are filtered out in the preprocessor run, i dont think so
这取决于预处理器如何处理注释和宏。如果它在宏扩展后删除注释,那么您的航行就会一帆风顺,但否则它可能仅仅由于预处理器的实现而无法工作。
你可以试试这个吗? (虽然会很乱)。
It would depend on how the preprocessor worked with comments and macros. If it strips comments after macro expansion then your smooth sailing, but otherwise it might not work simply due to the preprocessor implementation.
You could try this? (it would be messy though).
预处理器会删除注释部分。尝试运行
这将在您的代码上运行预处理器,但不会实际编译它,从而允许您查看宏扩展后会发生什么。您应该注意到,所有扩展宏中的所有注释都消失了。
The preprocessor strips out commented sections. Try running
This will run the preprocessor on your code but will not actually compile it, allowing you to see what happens after macro expansion. You should notice that all the comments are gone from any expanded macros.