此处当代码可以调用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.
更多推荐
我应该使用哪些编译标志来避免运行时错误
发布评论