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

Which compilation flags should I use to avoid run time errors

刚刚了解到 -Wsequence-point 编译标志会在代码可以调用 UB 时弹出警告。我在

这样的语句中尝试过
int x = 1;
int y = x+ ++x;

而且效果很好。到目前为止,我只使用 gccg++ 编译过 -ansi -pedantic -Wall 。你有任何其他有用的标志来使代码更安全和健壮吗?

正如 alk 总结的那样,使用这些标志:

-pedantic -Wall -Wextra -Wconversion


首先,我认为您不想使用 -ansi 标志,正如 Should I use "-ansi" or explicit "-std=..." as compiler flags?

中所建议的那样

其次,-Wextra seems to be quite useful too, as suggested in -Wextra how useful is it really?

第三,-Wconversion seems also useful, as suggested in Can I make GCC warn on passing too-wide types to functions?

第四,-pedantic也很有帮助, 如 What is the purpose of using -pedantic in GCC/G++ compiler?.

中所建议

最后,在这种情况下启用-Wall应该没问题,所以我对你说的很怀疑。

示例

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

示例 ,相同版本:

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.

我的相关 answer,Wall 再次解决了类似问题。