I was looking for a list of recommended g++ warning options for C++ and only could find this: Recommended gcc warning options for C and Useful GCC flags for C which are all quite C specific
-Wall and -Wextra enable most but not all of the warnings gcc can generate.
Which warnings that aren't enabled by those options especially when compiling C++ should be turned on as well?
-Wall -Wextra tends to cover the really noteworthy ones. Personally, I also like to compile with -ansi -pedantic and occasionally -Wshadow.
Also, it can be a little noisy and not useful 100% of the time, but -Weffc++ sometimes has good suggestions for better code quality as well.
EDIT In the age of modern C++, you should replace -ansi -pedantic with -std=c++14 -pedantic or whatever your version of choice is, since -ansi will put the compiler into C++98/C++-03 mode.
Don't forget -Wstrict-aliasing.
I found this post was good, look the params up:
Recommended gcc warning options for C
Related
I have a single C++14 file, my.cpp, and from within it I'm trying to use a C99 library called open62541. For the latter, both full source open62541.c/.h and a library libopen62541.a exist. In my.cpp, where I include the open62541.h, I'm using C++ specific code (e.g. iostream), so technically I'm mixing C and C++.
I can get my.cpp to compile successfully by referencing the libopen62541.a:
gcc -x c++ -std=c++14 -Wall my.cpp -l:libopen62541.a -lstdc++ -o out
This outputs no warnings, and creates an executable out.
However, if I try to compile using source code only:
gcc -x c++ -std=c++14 -Wall my.cpp open62541.c -lstdc++ -o out
I get a lot of ISO C++ warnings (e.g. "ISO C++ forbids converting a string constant to ‘char'*") and some "jump to label" errors originating from within open62541.c, resulting in compilation failure.
I can get compilation to succeed by using the -fpermissive switch:
gcc -x c++ -std=c++14 -Wall my.cpp open62541.c -lstdc++ -fpermissive -o out
which still outputs a lot of warnings, but creates the executable successfully. However, I'm unsure if doing this is a good idea.
Perhaps worth mentioning is that open62541.h considers C++ at the beginning:
#ifdef __cplusplus
extern "C" {
#endif
Given that .a library, which comes bundled with the open62541 library code, is supposedly built from the same source, why are the first two approaches not consistent in terms of warnings and errors generated? Why does one work and the other doesn't?
Should one method - linking .a vs referring to .c - be preferred to another? I was under impression that they should be equivalent, but apparently they aren't.
Is using -fpermissive in this case more of a hack that could mask potential problems, and should thus be avoided?
The error (and warning) you see are compilation errors (and warning) output by a C++ compiler when compiling C code.
For instance, in C "literal" has type char[] while in C++ it has type const char[].
Would you get a C++ compiler build libopen62541.a from open62541.c, you would see the same errors (warnings). But a C compiler might be OK with it (depending on the state of that C source file).
On the other hand, when you compile my.cpp and links it against libopen62541.a, the compiler doesn't see that offending C code, so no errors (warnings).
From here, you basically have two options:
Use the procompiled library if it suits you as is
g++ -std=c++14 -Wall -Wextra -Werror my.cpp -lopen62541.a -o out
Compile the library's code as a first step if you need to modify it
gcc -Wall -Wextra -Werror -c open62541.c
g++ -std=c++14 -Wall -Wextra -Werror -c my.cpp
g++ open62541.o my.o -o out
gcc -x c++ -std=c++14 -Wall my.cpp open62541.c -lstdc++ -o out
This command forces the C code in open62541.c to be compiled as C++. That file apparently contains constructs that are valid in C but not C++.
What you should be doing is compiling each file as its own language and then linking them together:
gcc -std=gnu11 -Wall -c open62541.c
g++ -std=gnu++14 -Wall -c my.cpp
g++ -o out my.o open62541.o
Wrapping up those commands in an easily repeatable package is what Makefiles are for.
If you're wondering why I changed from the strict -std=c++14 to the loose -std=gnu++14 mode, it's because the strict mode is so strict that it may break the system headers! You don't need to deal with that on top of everything else. If you want a more practical additional amount of strictness, try adding -Wextra and -Wpedantic instead ... but be prepared for that to throw lots of warnings that don't actually indicate bugs, on the third-party code.
I'm new to nvcc and I've seen a library where compilation is done with option -O3, for g++ and nvcc.
CC=g++
CFLAGS=--std=c++11 -O3
NVCC=nvcc
NVCCFLAGS=--std=c++11 -arch sm_20 -O3
What is -O3 doing ?
It's optimization on level 3, basically a shortcut for
several other options related to speed optimization etc. (see link below).
I can't find any documentation on it.
... it is one of the best known options:
https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html
http://docs.nvidia.com/cuda/cuda-compiler-driver-nvcc/#options-for-altering-compiler-linker-behavior
I installed Intel Compiler composer_xe_2013_sp1.3.174 on Linux. I am confused about the icc warnings. Feed icc with a simple program main.c as below:
int main(int argc, char **argv) {
int a = 1;
unsigned int b = -22;
if (b = a) {
}
}
I compiled the file with the command: icc -Wall main.c. Surprisingly, the command works silently without any warnings. Do I have to turn on the warnings switch on icc? Thanks
The Intel compiler doesn't really have good presets for warnings the way that gcc does (at least on Linux). The main warning option is -wn where n can be 0 to 5. The default is 1, and 4 & 5 have no meaning on Linux. It also supports some gcc options like -Wall and -Wextra. However:
-Wall is very minimalistic compared to gcc, as you found
-w2 and -w3 enable some useful diagnostics, but also a lot of spam remarks
-diag-disable:remark removes that spam but also a lot of useful diagnostics
In the end -w3 -diag-disable:remark is the best preset that icc has but it is still more minimalistic than gcc -Wall. Instead you need to either start with a minimal set of warnings and build up your own, or start with maximum diagnostics and disable any that get annoying using -wd.
Build Up
The main downside to the first approach is that Intel doesn't really document most of its warnings, so it is hard to know what is available to enable. However, it does support many of the GCC command line flags, so the GCC documentation is a good place to start. For example, here are settings that are relatively close to g++ -Wall, which is convenient if you want to develop with one and have a good chance of a clean build with the other:
icpc -Wall -Warray-bounds -Wchar-subscripts -Wcomment -Wenum-compare -Wformat -Wuninitialized -Wmaybe-uninitialized -Wmain -Wnarrowing -Wnonnull -Wparentheses -Wpointer-sign -Wreorder -Wreturn-type -Wsign-compare -Wsequence-point -Wtrigraphs -Wunused-function -Wunused-but-set-variable -Wunused-variable -Wwrite-strings
This isn't an exact match for gcc -Wall. There are differences between GCC's and ICC's implementation of the above warnings. I was also unable to find ICC options to match these GCC warnings:
-Wformat-contains-nul
-Wunused-label
-Wstrict-overflow
-Wvolatile-register-var
And I intentionally left these out, because the ICC version was much more spammy than GCC:
-Wstrict-aliasing So broad that any use of polymophism will cause this warning
-Wswitch Requires a default even if you have cases for all enumeration values
Trim Down
If GCC parity isn't a concern then the easiest way to learn what warnings ICC has is to enable them all, and then decide whether you like them or not. If you don't like a warning, you can disable it using it's diagnostics number, which often has more granularity that GCC's options do.
icpc -w3 -wd1418,2259
Here are some diagnostics that I have seen disabled in the past:
383: value copied to temporary, reference to temporary used
869: parameter "*" was never referenced
981: operands are evaluated in unspecified order
1418: external function definition with no prior declaration
1572: floating-point equality and inequality comparisons are unreliable
2259: non-pointer conversion may loose significant bits
11074: Inlining inhibited by limit max-size (or max-total-size)
11076: To get full report use -qopt-report=4 -qopt-report-phase ipo
161: disable warning for unrecognized pragmas
But I encourage you to start with them all on and pare down just the ones that are problematic for your code base.
Generally speaking, the best compilation options for a small program your developing is
-Wall -Wextra -std=c11 -pedantic
Contrary to the warning switch's name, Wall does not actually activate all warnings; you use both Wall and Wextra to get the majority of the important warnings.
-std switch sets the standard that the code uses; the most recent one is C11 therefore std=c11. Pedantic is a way to signal to the compiler that you want to write a program that doesn't use compiler-specific extensions. Pedantic requires the std switch and will emit warnings for any syntax, ect. that does not conform to the standard specified by std. Finally, if you want errors instead of warnings for usage of compiler-extension, use -pedantic-errors instead.*
(* - pedantic does not warn about the usage of non-standard libraries like conio.h)
Now if you compile the program with Wall Wextra std=c11 pedantic, you should get 1 warnings:
Warning: Line 4 - Suggest Parenthesis around truthy value (9 out of 10, this means you used = instead == in a comparison context).
If you fix that warning, you'll receive another warning:
Warning: Line 4 - Comparison between Signed and Unsigned Integer without a cast.
Adding an explicit cast or changing b to a normal int will solve this warning.
These days I am pretty happy using this target_options in CMake with icpc 2021.6.0 20220226, I collected them from several sources.
Any additions are welcome.
target_compile_options(
${TEST_EXE}
PRIVATE
$<$<COMPILE_LANG_AND_ID:CUDA,NVIDIA>:
...
>
$<$<AND:$<CXX_COMPILER_ID:GNU>,$<NOT:$<CUDA_COMPILER_ID:NVIDIA>>,$<NOT:$<CUDA_COMPILER_ID:Clang>>>:
...
>
$<$<OR:$<CXX_COMPILER_ID:Clang>,$<CXX_COMPILER_ID:AppleClang>,$<CUDA_COMPILER_ID:Clang>>:
...
>
$<$<CXX_COMPILER_ID:Intel>: # also IntelLLVM, XL (ibm), XLClang (ibm)
-Werror
-Wall
-Wextra
-diag-disable=remark
-diag-error:3846
-diag-disable=1011 # disables warning missing return at the end of non-void function
-wd161
-Wabi
-Warray-bounds
-Wcast-qual
-Wchar-subscripts
-Wcomment
-Wdeprecated
-Wenum-compare
-Wextra-tokens
-Wformat
-Wformat=2
-Wformat-security
-Wic-pointer
-Wnarrowing
-Wno-return-type
-Wnon-virtual-dtor
-Wnonnull
-Wmaybe-uninitialized
-Wmain
-Wmissing-declarations
-Wmissing-prototypes
-Wmultichar
-Woverloaded-virtual
-Woverflow
-Wparentheses
-Wpointer-arith
-Wpointer-sign
-Wreorder
-Wreturn-type
-Wsequence-point
-Wshadow
-Wsign-compare
-Wshorten-64-to-32
-Wno-strict-aliasing
-Wstrict-prototypes
-Wtrigraphs
-Wtype-limits
-Wuninitialized
-Wunused
-Wunused-but-set-variable
-Wunused-function
-Wunused-parameter
-Wunused-variable
-Wwrite-strings
>
$<$<OR:$<CXX_COMPILER_ID:PGI>,$<CXX_COMPILER_ID:NVHPC>>:
...
>
$<$<CXX_COMPILER_ID:MSVC>:
...
>
)
I'm working on a large collaborative C++ project that is both developed and run on various flavors of Linux, OS X and Windows. We compile across these platforms with GCC, Visual Studio C++ and the Intel C++ compiler. As more and more people start developing code for the project, we're starting to see weird errors in compilation and runtime that are specific to particular compilers on particular operating systems. An example of this is implicit inclusion of headers that certain OS/compiler pairs seem to find for you, accidentally overloading a function from a base class in a derived class.
My goal is to make compilation on GCC more strict and catch more errors across all platforms so that we don't keep running into these problems. Here's my list of flags that I'm thinking about trying out for GCC that I've found via Google and the GCC man pages:
-Wall
-Wextra
-Winit-self
-Wold-style-cast
-Woverloaded-virtual
-Wuninitialized
-Wmissing-declarations
-Winit-self
-ansi
-pedantic
What are the other flags that people use to make GCC (and less importantly Visual Studio C++ and the Intel C++ Compiler) obey a stricter standard of the C++ language? Be specific about which compiler and version you're talking about, as some of these might not be implemented in all versions of all compilers.
Beside the pedantic-error that everyone else suggested, IMO, it's always good to run lint as part of your compile process.
There are some tools out there:
cpplint (free)
gimple lint
coverity
They will save a lot of your time.
You can make pedantic warnings into errors with -pedantic-errors. This will prevent developers from ignoring it. For that matter you could make all warnings into errors as well with -Werror although that can be counter productive in some cases (maybe not in yours though).
Overall, I think, as far as adhering to a strict standard goes, the -pedantic options are the most helpful.
Copy and paste the below line into your master CMake file. The below line comprises almost most useful compiler flags in order to test yourself stricter.
set(CMAKE_CXX_FLAGS "-O0 -fno-elide-constructors -pedantic-errors -ansi -Wextra -Wall -Winit-self -Wold-style-cast -Woverloaded-virtual -Wuninitialized -Wmissing-declarations -Winit-self -std=c++98")
If you don’t use CMake, just copy the flags in double quotes and send them to your compiler.
-pedantic-errors.
See more on gcc(1).
As well as -pendantic, you should also provide a -std switch. If you need a stricter compile then you should know what standard you are trying to conform to. Typically for current C++ this would be -std=c++98. (-ansi performs a similar function in C++ mode, but -std= is more explicit.)
In a similar situation we gave up and moved to the ACE framework, hiding the difference between platforms.
I wrote a blog post on this topic after researching several options. You also need to handle the cases where you are using other libraries, but they are not following strict compilation. Fortunately, there is an easy way to handle them as well. I have been using this extensively in all my projects.
In short, use the following compiler options to turn on very strict mode (below is what I put in CMakeLists.txt):
set(CMAKE_CXX_FLAGS "-std=c++11 -Wall -Wextra -Wstrict-aliasing -pedantic -fmax-errors=5 -Werror -Wunreachable-code -Wcast-align -Wcast-qual -Wctor-dtor-privacy -Wdisabled-optimization -Wformat=2 -Winit-self -Wlogical-op -Wmissing-include-dirs -Wnoexcept -Wold-style-cast -Woverloaded-virtual -Wredundant-decls -Wshadow -Wsign-promo -Wstrict-null-sentinel -Wstrict-overflow=5 -Wswitch-default -Wundef -Wno-unused -Wno-variadic-macros -Wno-parentheses -fdiagnostics-show-option ${CMAKE_CXX_FLAGS}")
You can read more about how to turn on and off this strict mode for specific portions of code here: http://shitalshah.com/p/how-to-enable-and-use-gcc-strict-mode-compilation/
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
What compiler warning level do you recommend for different C/C++ compilers?
gcc and g++ will let you get away with a lot on the default level. I find the best warning level for me is '-Wall'. And I always try to remove fix the code for the warnings it generates. (Even the silly ones about using parenthesis for logical precedence rules or to say I really mean 'if (x = y)')
What are your favorite levels for the different compilers, such as Sun CC, aCC (HPUX ?), Visual Studio, intel?
Edit:
I just wanted to point out that I don't use "-Werror" (but I do understand it's utility) on gcc/g++ because, I use:
#warning "this is a note to myself"
in a few places in my code. Do all the compilers understand the #warning macro?
This is a set of extra-paranoid flags I'm using for C++ code:
-g -O -Wall -Weffc++ -pedantic \
-pedantic-errors -Wextra -Waggregate-return -Wcast-align \
-Wcast-qual -Wchar-subscripts -Wcomment -Wconversion \
-Wdisabled-optimization \
-Werror -Wfloat-equal -Wformat -Wformat=2 \
-Wformat-nonliteral -Wformat-security \
-Wformat-y2k \
-Wimplicit -Wimport -Winit-self -Winline \
-Winvalid-pch \
-Wunsafe-loop-optimizations -Wlong-long -Wmissing-braces \
-Wmissing-field-initializers -Wmissing-format-attribute \
-Wmissing-include-dirs -Wmissing-noreturn \
-Wpacked -Wpadded -Wparentheses -Wpointer-arith \
-Wredundant-decls -Wreturn-type \
-Wsequence-point -Wshadow -Wsign-compare -Wstack-protector \
-Wstrict-aliasing -Wstrict-aliasing=2 -Wswitch -Wswitch-default \
-Wswitch-enum -Wtrigraphs -Wuninitialized \
-Wunknown-pragmas -Wunreachable-code -Wunused \
-Wunused-function -Wunused-label -Wunused-parameter \
-Wunused-value -Wunused-variable -Wvariadic-macros \
-Wvolatile-register-var -Wwrite-strings
That should give you something to get started. Depending on a project, you might need to tone it down in order to not see warning coming from third-party libraries (which are usually pretty careless about being warning free.) For example, Boost vector/matrix code will make g++ emit a lot of noise.
A better way to handle such cases is to write a wrapper around g++ that still uses warnings tuned up to max but allows one to suppress them from being seen for specific files/line numbers. I wrote such a tool long time ago and will release it once I have time to clean it up.
On Visual C++, I use /W4 and /WX (treat warnings as errors).
VC also has /Wall, but it's incompatible with the standard headers.
I choose to treat warnings as errors, because that forces me to fix them. I fix all warnings, even if that means adding #pragma to ignore the warning - that way, I'm stating explicitly, that I'm aware of the warning (so other developers won't e-mail me about it).
I believe VC also supports
#pragma message ("note to self")
But as the system grows and grows, and you get a nightly build 30 developers work on simultaneously, it takes days to read all the notes to self, even in that amount that self is going to be do nothing but note reading and finally going to break under the stress not being able to keep up and have to resign...
No really, the amount of warnings is quickly going to grow if you allow them, and you won't be able to spot the really important ones (uninitialized variables, this pointer used in constructor, ...).
That's why I try to treat warnings as errors: most of the time, the compiler is right warning me, and if he isn't, I document it in the code and prepend
#pragma warning ( push )
#pragma warning ( 4191 : disable )
// violent code, properly documented
#pragma warning ( pop )
I just read they have a warning ( N : suppress ) pragma, too.
I tend to use -Wall (because everyone does make bugs, nobody is perfect) , but i don't use -Werror (treat warnings as errors) because now and then gcc warns about things which are right anyway (false positives).
I agree with litb to always use -Wall. In addition, if you want to ensure your code is compliant you can also use -pedantic. Another warning that can be helpful if you're handling unions and structs at the byte level is -Wpadded.
I do all development with Warning as Errors turned on.
Since I still develop in VC6 I have a lot of #pragma's in my code (4786 mainly).
There's a nice list of options for GCC here: http://mces.blogspot.com/2008/12/year-end-cleaning-ie-on-warning-options.htm.
-Wall does not enable all the possible warnings, and some have to be enabled explicitely.
I like -Wall and strict prototypes as well as implicit function definitions. Errors on those can be very useful. There's also -Wextra which will pick up all kinds of things like things you intended to be conditionals but accidentally wrote as statements:
if (something);
classic_way_to_leak_memory();
On Unix-like systems you have to obey the user's ENV preferences .. so what they see and report might be entirely different than what you need :)
I'm also a type punning fiend, so I tend to set -Fno-strict-aliasing as well, unless the user wants it. Safe memory management in classic C is hard to accomplish otherwise.
no one has mentioned the Intel compiler yet:
https://software.intel.com/sites/products/documentation/doclib/iss/2013/compiler/cpp-lin/GUID-D060680A-1A18-4574-8291-5C74E6E31335.htm
-w3 is pretty chatty, so I would suggest -w2
On GCC, for preference I use -Wall -Wextra -Wwrite-strings -Werror, and also specify a standard with std=. Which standard depends on the project: principally on how portable it needs to be.
The reason I use -Werror is that warnings are unacceptable (to me) even if they don't represent a real bug. I'd rather work around whatever caused the warning, than have to ignore warnings every single time I compile for the rest of my life. Once you allow warnings in the compile, it's just too easy to miss one that wasn't there last time.
Of course when dealing with third-party code, sometimes you can't get rid of the warnings. Then I'd decide on a case-by-case basis whether to relax the -W options, remove -Werror and write a script to check that only expect warnings occur, or maybe modify the third-party code (either to "fix" the warning or to disable it with pragmas if possible).
In Visual C I use /w3. I find w4 throws up too much noise (lots of it from the MS libraries) to go through on every build. The extra warnings are very minor and haven't been a cause of a bug so far.
I also like check all possible warnings that give compiler in my project. Unfortunately answer about Intel C++ compiler was not very informative for me (link is dead). I made my own research.
Because i use Qt 5 and qmake i have predefined warning level -w1. Can't do nothing with that. But this is not all and ICC has more keys:
-Wcomment
-Weffc++
-Wextra-tokens
-Wformat
-Winline // don't use, show only for example
-Wmain
-Wmissing-declarations
-Wmissing-prototypes
-Wnon-virtual-dtor
-Wp64
-Wpointer-arith
-Wremarks
-Wreturn-type
-Wsign-compare
-Wstrict-aliasing
-Wstrict-prototypes
-Wtrigraphs
-Wuninitialized
-Wunknown-pragmas
-Wunused-variable
More about all keys.
Also i want to add that, unlike GCC, ICC produces several warnings for one key, for example key -Weffc++. In case you want only see several warnings from all list use key -wd.
I disable: -wd1418,2012,2015,2017,2022,2013. And warnings -wd1572,873,2259,2261 was disabled in qmake by default.
I use PCH and have found very annoying to see in Qt Creator messages about using PCH file like error. To disable, use -Wno-pch-messages.
For disabling warning in code i use:
#if defined(Q_CC_INTEL)
#pragma warning( push )
#pragma warning( disable: 2021 )
#endif
// some code
#if defined(Q_CC_INTEL)
#pragma warning( pop )
#endif
Thanks everyone for their answers. It has been a while since I've used anything but gcc/g++. Ones I've had to use a long time ago are
-fmessage-length = 0 (since g++ had an ugly habit of line breaking messages)
-Wno-deprecated (since I worked on a code base pre-existing the std namespace)
I do remember that (at least 5 years ago) anything above the default warning level on the Sun Workshop CC compiler was too much. I also think this may have been true for the Intel compiler. I have not been up to date with non gnu compilers for a while.
The GCC compilers become stricter with every new version. Use the flag -ansi to produce warnings for violations of the strictest interpretation of the ANSI language standards. That's usually stuff that just happens to work in your current compiler, but may produce errors in the next version or in other compilers. That flag will help you avoid having to port your code every time you switch compilers/versions.