如何使用gcc捕获未定义的预处理器宏?

编程入门 行业动态 更新时间:2024-10-25 06:33:06
本文介绍了如何使用gcc捕获未定义的预处理器宏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我一直在研究一段代码,里面有一个被忽略的derp:

I've been working on a piece of code that had an overlooked derp in it:

#include<stdio.h> #include<stdlib.h> #include<limits.h> #define MAX_N_LENGTH /*function prototypes*/ int main(){ ... }

删除上下文应该很容易发现:#define MAX_N_LENGTH应该读为#define MAX_N_LENGTH 9.我不知道那个尾随常数在哪里.

It should be easy to spot with the context removed: #define MAX_N_LENGTH should have read #define MAX_N_LENGTH 9. I have no idea where that trailing constant went.

由于宏仅以char buf[ MAX_N_LENGTH + 1]的形式在一个地方使用,因此很难跟踪和调试程序.

Since that macro was only used in one place in the form of char buf[ MAX_N_LENGTH + 1], it was extremely difficult to track down and debug the program.

是否有一种方法可以使用gcc编译器捕获此类错误?

Is there a way to catch errors like this one using the gcc compiler?

推荐答案

从一般意义上讲,不可能捕获此错误,因为它不是错误.在很多情况下,都需要这种行为,因此编译器无法将其视为错误或警告.

It's not possible to catch this error in the general sense, because it isn't an error. There's plenty of cases where this sort of behavior is desired, so the compiler cannot treat it as an error or a warning.

如果您可以将错误跟踪到一行,则使用gcc的-E命令行参数将导致其输出预处理器的结果.在这种情况下,您的字符行将变为char buf[+1],这是合法的C代码,但可能会引起您的注意,因为您希望它是char buf[9+1]. -E导致gcc打印这些结果,因此您实际上会在gcc的输出中看到char buf[+1].

If you can track the error down to a line, using gcc's -E command line argument will cause it to output the result of the preprocessor. In that case, your char line would have turned to char buf[+1], which is legal C code, but might catch your attention because you expected it to be char buf[9+1]. -E causes gcc to print those results, so you would actually see char buf[+1] in the output of gcc.

像这样的问题是为什么C ++不鼓励这样使用define宏的原因(当然,C ++比C具有更多的替代选择,因此更不鼓励使用它们)

Issues like this are why C++ discourages use of define macros in this way (C++, of course, has more alternatives than C which makes it easier to discourage them)

更多推荐

如何使用gcc捕获未定义的预处理器宏?

本文发布于:2023-11-11 10:48:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1578208.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   未定义   gcc

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!