如何使用gcc捕获未定义的预处理器宏? [英] How to catch undefined preprocessor macro with gcc?

查看:119
本文介绍了如何使用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捕获未定义的预处理器宏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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