Why should I always enable compiler warnings?

后端 未结 20 1589
时光说笑
时光说笑 2020-11-22 00:28

I often hear that when compiling C and C++ programs I should \"always enable compiler warnings\". Why is this necessary? How do I do that?

Sometimes I also hear tha

相关标签:
20条回答
  • 2020-11-22 01:11

    Treating warnings as errors is just a mean of self-discipline: you were compiling a program to test that shiny new feature, but you can't until you fix the sloppy parts. There is no additional information Werror provides, it just sets priorities very clearly:

    Don't add new code until you fix problems in the existing code

    It's really the mindset that's important, not the tools. Compiler diagnostics output is a tool. MISRA (for embedded C) is another tool. It doesn't matter which one you use, but arguably compiler warnings is the easiest tool you can get (it's just one flag to set) and the signal to noise ratio is very high. So there's no reason not to use it.

    No tool is infallible. If you write const float pi = 3.14;, most tools won't tell you that you defined π with a bad precision which may lead to problems down the road. Most tools won't raise an eyebrow on if(tmp < 42), even if it's commonly known that giving variables meaningless names and using magic numbers is a way to disaster in big projects. You have to understand that any "quick test" code you write is just that: a test, and you have to get it right before you move on to other tasks, while you still see its shortcomings. If you leave that codes as is, debugging if after you spend two months adding new features will be significantly harder.

    Once you get into the right mindset, there is no point in using Werror. Having warnings as warnings will allow you to take an informed decision whether it still makes sense to run that debug session you were about to start, or to abort it and fix the warnings first.

    0 讨论(0)
  • 2020-11-22 01:12

    You should definitely enable compiler warnings as some compilers are bad at reporting some common programming mistakes, including the following:-

    -> initialise a variable gets forgotten -> return a value from a function get missed -> the simple arguments in printf and scanf families not matching the format string a function is used without being declared beforehand, though happens in c only

    So as these functions can be detected and reported, just usually not by default; so this feature must be explicitly requested via compiler options.

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