我应该使用哪些编译标志来避免运行时错误

编程入门 行业动态 更新时间:2024-10-09 23:20:48
本文介绍了我应该使用哪些编译标志来避免运行时错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

此处当代码可以调用UB时,c0> comiplation标志将弹出警告.我在

Just learned here that -Wsequence-point comiplation flag will pop a warning when the code can invoke UB. I tried it on a statement like

int x = 1; int y = x+ ++x;

,效果很好.到目前为止,我仅使用-ansi -pedantic -Wall来使用gcc或g++进行编译.您还有其他有用的标志来使代码更安全,更可靠吗?

and it worked very nicely. Until now I have compiled with gcc or g++ only using -ansi -pedantic -Wall . Do you have any other helpful flags to make the code more safe and robust?

推荐答案

对alk进行总结时,请使用以下标志:

As alk summed up, use these flags:

-pedantic -Wall -Wextra -Wconversion

-pedantic -Wall -Wextra -Wconversion

首先,我认为您不想使用-ansi标志,如我应该使用"-ansi"或显式"-std = ..."作为编译器标志?

First, I think you don't want to use the -ansi flag, as suggested in Should I use "-ansi" or explicit "-std=..." as compiler flags?

其次, -Wextra 似乎也非常有用,如 -Wextra真正有用吗?

第三, -Wconversion 似乎也有用,如中的建议一样GCC是否警告将过大的类型传递给函数?

第四, -pedantic 也是有帮助的 如中所建议的- .

Fourthly, -pedantic is also helpul, as suggested in What is the purpose of using -pedantic in GCC/G++ compiler?.

最后,在这种情况下,启用-Wall应该很好,所以我对您的发言表示怀疑.

Lastly, enabling -Wall should be fine in this case, so I am pretty doubtful about what you said.

带有 gcc 的问题:

Georgioss-MacBook-Pro:~ gsamaras$ cat main.c int main(void) { int x = 1; int y = x+ ++x; return 0; } Georgioss-MacBook-Pro:~ gsamaras$ gcc -Wall main.c main.c:4:16: warning: unsequenced modification and access to 'x' [-Wunsequenced] int y = x+ ++x; ~ ^ main.c:4:9: warning: unused variable 'y' [-Wunused-variable] int y = x+ ++x; ^ 2 warnings generated. Georgioss-MacBook-Pro:~ gsamaras$ gcc -v Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/usr/include/c++/4.2.1 Apple LLVM version 8.1.0 (clang-802.0.38) Target: x86_64-apple-darwin16.3.0 Thread model: posix InstalledDir: /Library/Developer/CommandLineTools/usr/bin

带有 g ++ 的问题的示例,相同的版本:

Example with g++, same version:

Georgioss-MacBook-Pro:~ gsamaras$ cp main.c main.cpp Georgioss-MacBook-Pro:~ gsamaras$ g++ -Wall main.cpp main.cpp:4:16: warning: unsequenced modification and access to 'x' [-Wunsequenced] int y = x+ ++x; ~ ^ main.cpp:4:9: warning: unused variable 'y' [-Wunused-variable] int y = x+ ++x; ^ 2 warnings generated.

与我的相关的答案,沃尔因类似的问题再次节省了时间.

Relevant answer of mine, that Wall saves the day once more with a similar problem.

更多推荐

我应该使用哪些编译标志来避免运行时错误

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

发布评论

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

>www.elefans.com

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