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

CIs*_*ies 8 c c++ compiler-flags compiler-warnings sequence-points

刚刚在这里学到,-Wsequence-point当代码可以调用UB时,comiplation标志会弹出警告.我在类似的声明上尝试过

int x = 1;
int y = x+ ++x;
Run Code Online (Sandbox Code Playgroud)

它工作得非常好.到目前为止,我已编译gcc或g++仅使用-ansi -pedantic -Wall.你有没有其他有用的标志来使代码更安全和健壮?

gsa*_*ras 5

总结起来,使用这些标志:

-pedantic -Wall -Wextra -Wconversion


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

其次,-Wextra似乎也非常有用,正如-Wextra中所建议的那样它真的有用吗?

第三,-Wconversion似乎也很有用,如我所说,我可以让GCC警告将过多的类型传递给函数吗?

第四,-pedantic也是帮助,如在GCC/G ++编译器中使用-pedantic的目的是什么建议的?.

最后,-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
Run Code Online (Sandbox Code Playgroud)

示例,相同版本:

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.
Run Code Online (Sandbox Code Playgroud)

我的相关答案是,Wall再次以类似的问题挽救了这一天.

  • 注意:`-Wall`不启用*all*警告 - 实际上远非它.就个人而言,我总是至少添加`-Wextra`.但即使这样仍然无法启用所有有用的警告,您可能还需要启用许多其他警告. (5认同)