Which flag compilations should be used to avoid runtime errors

I just found out here that the -Wsequence-point comiplation flag will alert when code can call UB. I tried this in a statement like

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

and it worked very well. So far, I compiled with gcc or g++ only with -ansi -pedantic -Wall . Do you have other useful flags to make your code more secure and reliable?

+7
c ++ c sequence-points compiler-warnings compiler-flags
source share
1 answer

As the alk statement suggests, use these flags:

-pedantic -Wall -Wextra -Wconversion


Firstly, I think you do not want to use the -ansi flag, as suggested in Should I use "-ansi" or explicit "-std = ..." as compiler flags?

Secondly, -Wextra seems very useful, as suggested in -Wextra how useful is it?

Thirdly, it seems that -Wconversion , as suggested in Can I make a GCC warning when passing too wide function types?

Fourth, -pedantic also helps, as suggested in What is the purpose of using -pedantic in the GCC / g ++ compiler? .

Finally, including -Wall should be fine in this case, so I pretty much doubt 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 

G ++ example, 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. 

Relevantly answer that Wall again saves a day with a similar problem.

+5
source share

All Articles