Which compilation flags should I use to avoid run time errors

前端 未结 1 1046
暖寄归人
暖寄归人 2020-12-16 04:23

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条回答
  • 2020-12-16 04:40

    As alk summed up, use these flags:

    -pedantic -Wall -Wextra -Wconversion


    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?

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

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

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

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

    Example with 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
    

    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.

    0 讨论(0)
提交回复
热议问题