Movatterモバイル変換


[0]ホーム

URL:


Next:, Previous:, Up:GCC Command Options   [Contents][Index]


3.5 Options Controlling C++ Dialect

This section describes the command-line options that are only meaningfulfor C++ programs. You can also use most of the GNU compiler optionsregardless of what language your program is in. For example, youmight compile a filefirstClass.C like this:

g++ -g -fstrict-enums -O -c firstClass.C

In this example, only-fstrict-enums is an option meantonly for C++ programs; you can use the other options with anylanguage supported by GCC.

Some options for compiling C programs, such as-std, are alsorelevant for C++ programs.SeeOptions Controlling C Dialect.

Here is a list of options that areonly for compiling C++ programs:

-fabi-version=n

Use versionn of the C++ ABI. The default is version 0.

Version 0 refers to the version conforming most closely tothe C++ ABI specification. Therefore, the ABI obtained using version 0will change in different versions of G++ as ABI bugs are fixed.

Version 1 is the version of the C++ ABI that first appeared in G++ 3.2.

Version 2 is the version of the C++ ABI that first appeared in G++3.4, and was the default through G++ 4.9.

Version 3 corrects an error in mangling a constant address as atemplate argument.

Version 4, which first appeared in G++ 4.5, implements a standardmangling for vector types.

Version 5, which first appeared in G++ 4.6, corrects the mangling ofattribute const/volatile on function pointer types, decltype of aplain decl, and use of a function parameter in the declaration ofanother parameter.

Version 6, which first appeared in G++ 4.7, corrects the promotionbehavior of C++11 scoped enums and the mangling of template argumentpacks, const/static_cast, prefix ++ and –, and a class scope functionused as a template argument.

Version 7, which first appeared in G++ 4.8, that treats nullptr_t as abuiltin type and corrects the mangling of lambdas in default argumentscope.

Version 8, which first appeared in G++ 4.9, corrects the substitutionbehavior of function types with function-cv-qualifiers.

Version 9, which first appeared in G++ 5.2, corrects the alignment ofnullptr_t.

Version 10, which first appeared in G++ 6.1, adds mangling ofattributes that affect type identity, such as ia32 calling conventionattributes (e.g. ‘stdcall’).

Version 11, which first appeared in G++ 7, corrects the mangling ofsizeof... expressions and operator names. For multiple entities withthe same name within a function, that are declared in different scopes,the mangling now changes starting with the twelfth occurrence. It alsoimplies-fnew-inheriting-ctors.

Version 12, which first appeared in G++ 8, corrects the callingconventions for empty classes on the x86_64 target and for classeswith only deleted copy/move constructors. It accidentally changes thecalling convention for classes with a deleted copy constructor and atrivial move constructor.

Version 13, which first appeared in G++ 8.2, fixes the accidentalchange in version 12.

Version 14, which first appeared in G++ 10, corrects the mangling ofthe nullptr expression.

Version 15, which first appeared in G++ 10.3, corrects G++ 10 ABItag regression.

Version 16, which first appeared in G++ 11, changes the mangling of__alignof__ to be distinct from that ofalignof, anddependent operator names.

Version 17, which first appeared in G++ 12, fixes layout of classesthat inherit from aggregate classes with default member initializersin C++14 and up.

Version 18, which first appeared in G++ 13, fixes manglings of lambdasthat have additional context.

Version 19, which first appeared in G++ 14, fixes manglings ofstructured bindings to include ABI tags, handling of cv-qualified[[no_unique_address]] members, and adds mangling of C++20 constraintson function templates.

Version 20, which first appeared in G++ 15, fixes manglings of lambdasin static data member initializers.

Version 21, which first appeared in G++ 16, fixes unnecessary capturesin noexcept lambdas (c++/119764), layout of a base class with all explicitlydefaulted constructors (c++/120012), and mangling of class and arrayobjects with implicitly zero-initialized non-trailing subobjects (c++/121231).

See also-Wabi.

-fabi-compat-version=n

On targets that support strong aliases, G++works around mangling changes by creating an alias with the correctmangled name when defining a symbol with an incorrect mangled name.This switch specifies which ABI version to use for the alias.

With-fabi-version=0 (the default), this defaults to 13 (GCC 8.2compatibility). If another ABI version is explicitly selected, thisdefaults to 0. For compatibility with GCC versions 3.2 through 4.9,use-fabi-compat-version=2.

If this option is not provided but-Wabi=n is, thatversion is used for compatibility aliases. If this option is providedalong with-Wabi (without the version), the version from thisoption is used for the warning.

-fno-access-control

Turn off all access checking. This switch is mainly useful for workingaround bugs in the access control code.

-faligned-new
-faligned-new=alignment

Enable support for C++17new of types that require morealignment thanvoid* ::operator new(std::size_t) provides. Anumeric argument such as-faligned-new=32 can be used tospecify how much alignment (in bytes) is provided by that function,but few users will need to override the default ofalignof(std::max_align_t).

This flag is enabled by default for-std=c++17.

-fno-assume-sane-operators-new

The C++ standard allows replacing the globalnew,new[],delete anddelete[] operators, though a lot of C++ programsdon’t replace them and just use the implementation provided version.Furthermore, the C++ standard allows omitting those calls if they aremade from new or delete expressions (and by extension the same isassumed if__builtin_operator_new or__builtin_operator_deletefunctions are used).This option allows control over some optimizations around callsto those operators.With-fassume-sane-operators-new-delete option GCC may assume thatcalls to the replaceable global operators from new or delete expressions orfrom__builtin_operator_new or__builtin_operator_delete callsdon’t read or modify any global variables or variables whose address couldescape to the operators (global state; except forerrno for thenew andnew[] operators).This allows most optimizations across those calls and is something thatthe implementation provided operators satisfy unlessmallocimplementation details are observable in the code or unlessmallochooks are used, but might not be satisfied if a program replaces thoseoperators. This behavior is enabled by default.With-fno-assume-sane-operators-new-delete option GCC mustassume all these calls (whether from new or delete expressions or calleddirectly) may read and write global state unless proven otherwise (e.g.when GCC compiles their implementation). Use this option if thoseoperators are or may be replaced and code needs to expect such behavior.

-fchar8_t
-fno-char8_t

Enable support forchar8_t as adopted for C++20. This includesthe addition of a newchar8_t fundamental type, changes to thetypes of UTF-8 string and character literals, new signatures foruser-defined literals, associated standard library updates, and new__cpp_char8_t and__cpp_lib_char8_t feature test macros.

This option enables functions to be overloaded for ordinary and UTF-8strings:

int f(const char *);    // #1int f(const char8_t *); // #2int v1 = f("text");     // Calls #1int v2 = f(u8"text");   // Calls #2

and introduces new signatures for user-defined literals:

int operator""_udl1(char8_t);int v3 = u8'x'_udl1;int operator""_udl2(const char8_t*, std::size_t);int v4 = u8"text"_udl2;template<typename T, T...> int operator""_udl3();int v5 = u8"text"_udl3;

The change to the types of UTF-8 string and character literals introducesincompatibilities with ISO C++11 and later standards. For example, thefollowing code is well-formed under ISO C++11, but is ill-formed when-fchar8_t is specified.

const char *cp = u8"xx";// error: invalid conversion from                        //        `const char8_t*' to `const char*'int f(const char*);auto v = f(u8"xx");     // error: invalid conversion from                        //        `const char8_t*' to `const char*'std::string s{u8"xx"};  // error: no matching function for call to                        //        `std::basic_string<char>::basic_string()'using namespace std::literals;s = u8"xx"s;            // error: conversion from                        //        `basic_string<char8_t>' to non-scalar                        //        type `basic_string<char>' requested
-fcheck-new

Check that the pointer returned byoperator new is non-nullbefore attempting to modify the storage allocated. This check isnormally unnecessary because the C++ standard specifies thatoperator new only returns0 if it is declaredthrow(), in which case the compiler always checks thereturn value even without this option. In all other cases, whenoperator new has a non-empty exception specification, memoryexhaustion is signalled by throwingstd::bad_alloc. See also‘new (nothrow)’.

-fconcepts

Enable support for the C++ Concepts feature for constraining templatearguments. With-std=c++20 and above, Concepts are part ofthe language standard, so-fconcepts defaults to on.

Some constructs that were allowed by the earlier C++ Extensions forConcepts Technical Specification, ISO 19217 (2015), but didn’t make itinto the standard, could additionally be enabled by-fconcepts-ts. The option-fconcepts-ts was deprecatedin GCC 14 and removed in GCC 15; users are expected to convert their codeto C++20 concepts.

-fconcepts-diagnostics-depth=n

Specify maximum error replay depth during recursive diagnosis of a constraintsatisfaction failure. The default is 1.

-fconstexpr-depth=n

Set the maximum nested evaluation depth for C++11 constexpr functionston. A limit is needed to detect endless recursion duringconstant expression evaluation. The minimum specified by the standardis 512.

-fconstexpr-cache-depth=n

Set the maximum level of nested evaluation depth for C++11 constexprfunctions that will be cached ton. This is a heuristic thattrades off compilation speed (when the cache avoids repeatedcalculations) against memory consumption (when the cache grows verylarge from highly recursive evaluations). The default is 8. Very fewusers are likely to want to adjust it, but if your code does heavyconstexpr calculations you might want to experiment to find whichvalue works best for you.

-fconstexpr-fp-except

Annex F of the C standard specifies that IEC559 floating pointexceptions encountered at compile time should not stop compilation.C++ compilers have historically not followed this guidance, insteadtreating floating point division by zero as non-constant even thoughit has a well defined value. This flag tells the compiler to giveAnnex F priority over other rules saying that a particular operationis undefined.

constexpr float inf = 1./0.; // OK with -fconstexpr-fp-except
-fconstexpr-loop-limit=n

Set the maximum number of iterations for a loop in C++14 constexpr functionston. A limit is needed to detect infinite loops duringconstant expression evaluation. The default is 262144 (1<<18).

-fconstexpr-ops-limit=n

Set the maximum number of operations during a single constexpr evaluation.Even when number of iterations of a single loop is limited with the above limit,if there are several nested loops and each of them has many iterations but stillsmaller than the above limit, or if in a body of some loop or even outsideof a loop too many expressions need to be evaluated, the resulting constexprevaluation might take too long.The default is 33554432 (1<<25).

-fcontracts

Enable experimental support for the C++ Contracts feature, as brieflyadded to and then removed from the C++20 working paper (N4820). Theimplementation also includes proposed enhancements from papers P1290,P1332, and P1429. This functionality is intended mostly for thoseinterested in experimentation towards refining the feature to get itinto shape for a future C++ standard.

On violation of a checked contract, the violation handler is called.Users can replace the violation handler by defining

voidhandle_contract_violation (const std::experimental::contract_violation&);

There are different sets of additional flags that can be used togetherto specify which contracts will be checked and how, for N4820contracts, P1332 contracts, or P1429 contracts; these sets cannot beused together.

-fcontract-mode=[on|off]

Control whether any contracts have any semantics at all. Defaults to on.

-fcontract-assumption-mode=[on|off]

[N4820] Control whether contracts with level ‘axiom’should have the assume semantic. Defaults to on.

-fcontract-build-level=[off|default|audit]

[N4820] Specify which level of contracts to generate checksfor. Defaults to ‘default’.

-fcontract-continuation-mode=[on|off]

[N4820] Control whether to allow the program to continue executingafter a contract violation. That is, do checked contracts have the‘maybe’ semantic described below rather than the ‘never’semantic. Defaults to off.

-fcontract-role=name:default,audit,axiom

[P1332] Specify the concrete semantics for each contract levelof a particular contract role.

-fcontract-semantic=[default|audit|axiom]:semantic

[P1429] Specify the concrete semantic for a particularcontract level.

-fcontract-strict-declarations=[on|off]

Control whether to reject adding contracts to a function after itsfirst declaration. Defaults to off.

The possible concrete semantics for that can be specified with‘-fcontract-role’ or ‘-fcontract-semantic’ are:

ignore

This contract has no effect.

assume

This contract is treated like C++23[[assume]].

check_never_continue
never
abort

This contract is checked. If it fails, the violation handler iscalled. If the handler returns,std::terminate is called.

check_maybe_continue
maybe

This contract is checked. If it fails, the violation handler iscalled. If the handler returns, execution continues normally.

-fcoroutines

Enable support for the C++ coroutines extension (experimental).

-fdiagnostics-all-candidates

Permit the C++ front end to note all candidates during overload resolutionfailure, including when a deleted function is selected.

-fdump-lang-
-fdump-lang-switch
-fdump-lang-switch-options
-fdump-lang-switch-options=filename

Control the dumping of C++-specific information. Theoptionsandfilename portions behave as described in the-fdump-tree option. The followingswitch values areaccepted:

all

Enable all of the below.

class

Dump class hierarchy information. Virtual table information is emittedunless ’slim’ is specified.

module

Dump module information. Optionslineno (locations),graph (reachability),blocks (clusters),uid (serialization),alias (mergeable),asmname (Elrond),eh (mapper) &vops(macros) may provide additional information.

raw

Dump the raw internal tree data.

tinst

Dump the sequence of template instantiations, indented to show thedepth of recursion. Thelineno option adds the sourcelocation where the instantiation was triggered, and thedetails option also dumps pre-instantiation substitutionssuch as those performed during template argument deduction.

Lines in the .tinst dump start with ‘I’ for an instantiation,‘S’ for another substitution, and ‘R[IS]’ for the reopenedcontext of a deferred instantiation.

-fno-elide-constructors

The C++ standard allows an implementation to omit creating a temporarythat is only used to initialize another object of the same type.Specifying this option disables that optimization, and forces G++ tocall the copy constructor in all cases. This option also causes G++to call trivial member functions which otherwise would be expanded inline.

In C++17, the compiler is required to omit these temporaries, but thisoption still affects trivial member functions.

-fno-enforce-eh-specs

Don’t generate code to check for violation of exception specificationsat run time. This option violates the C++ standard, but may be usefulfor reducing code size in production builds, much like definingNDEBUG. This does not give user code permission to throwexceptions in violation of the exception specifications; the compilerstill optimizes based on the specifications, so throwing anunexpected exception results in undefined behavior at run time.

-fextern-tls-init
-fno-extern-tls-init

The C++11 and OpenMP standards allowthread_local andthreadprivate variables to have dynamic (runtime)initialization. To support this, any use of such a variable goesthrough a wrapper function that performs any necessary initialization.When the use and definition of the variable are in the sametranslation unit, this overhead can be optimized away, but when theuse is in a different translation unit there is significant overheadeven if the variable doesn’t actually need dynamic initialization. Ifthe programmer can be sure that no use of the variable in anon-defining TU needs to trigger dynamic initialization (eitherbecause the variable is statically initialized, or a use of thevariable in the defining TU will be executed before any uses inanother TU), they can avoid this overhead with the-fno-extern-tls-init option.

On targets that support symbol aliases, the default is-fextern-tls-init. On targets that do not support symbolaliases, the default is-fno-extern-tls-init.

-ffold-simple-inlines
-fno-fold-simple-inlines

Permit the C++ frontend to fold calls tostd::move,std::forward,std::addressof,std::to_underlyingandstd::as_const. In contrast to inlining, thismeans no debug information will be generated for such calls. Since thesefunctions are rarely interesting to debug, this flag is enabled by defaultunless-fno-inline is active.

-fno-gnu-keywords

Do not recognizetypeof as a keyword, so that code can use thisword as an identifier. You can use the keyword__typeof__ instead.This option is implied by the strict ISO C++ dialects:-ansi,-std=c++98,-std=c++11, etc.

-fno-immediate-escalation

Do not enable immediate function escalation whereby certain functionscan be promoted to consteval, as specified in P2564R3. For example:

consteval int id(int i) { return i; }constexpr int f(auto t){  return t + id(t); // id causes f<int> to be promoted to consteval}void g(int i){  f (3);}

compiles in C++20:f is an immediate-escalating function (due totheauto it is a function template and is declaredconstexpr)andid(t) is an immediate-escalating expression, sof ispromoted toconsteval. Consequently, the call toid(t)is in an immediate context, so doesn’t have to produce a constant (thatis the mechanism allowing consteval function composition). However,with-fno-immediate-escalation,f is not promoted toconsteval, and since the call to consteval functionid(t)is not a constant expression, the compiler rejects the code.

This option is turned on by default; it is only effective in C++20 modeor later.

-fimplicit-constexpr

Make inline functions implicitly constexpr, if they satisfy therequirements for a constexpr function. This option can be used inC++14 mode or later. This can result in initialization changing fromdynamic to static and other optimizations.

-fno-implicit-templates

Never emit code for non-inline templates that are instantiatedimplicitly (i.e. by use); only emit code for explicit instantiations.If you use this option, you must take care to structure your code toinclude all the necessary explicit instantiations to avoid gettingundefined symbols at link time.SeeWhere’s the Template?, for more information.

-fno-implicit-inline-templates

Don’t emit code for implicit instantiations of inline templates, either.The default is to handle inlines differently so that compiles with andwithout optimization need the same set of explicit instantiations.

-fno-implement-inlines

To save space, do not emit out-of-line copies of inline functionscontrolled by#pragma implementation. This causes linkererrors if these functions are not inlined everywhere they are called.

-fmodules
-fno-modules

Enable support for C++20 modules (seeC++ Modules). The-fno-modules is usually not needed, as that is thedefault. Even though this is a C++20 feature, it is not currentlyimplicitly enabled by selecting that standard version.

-fmodule-header
-fmodule-header=user
-fmodule-header=system

Compile a header file to create an importable header unit.

-fmodule-implicit-inline

Member functions defined in their class definitions are not implicitlyinline for modular code. This is different to traditional C++behavior, for good reasons. However, it may result in a difficultyduring code porting. This option makes such function definitionsimplicitly inline. It does however generate an ABI incompatibility,so you must use it everywhere or nowhere. (Such definitions outsideof a named module remain implicitly inline, regardless.)

-fno-module-lazy

Disable lazy module importing and module mapper creation.

-fmodule-mapper=[hostname]:port[?ident]
-fmodule-mapper=|program[?ident]args...
-fmodule-mapper==socket[?ident]
-fmodule-mapper=<>[inout][?ident]
-fmodule-mapper=<in>out[?ident]
-fmodule-mapper=file[?ident]

An oracle to query for module name to filename mappings. Ifunspecified theCXX_MODULE_MAPPER environment variable is used,and if that is unset, an in-process default is provided.

-fmodule-only

Only emit the Compiled Module Interface, inhibiting any object file.

-fms-extensions

Disable Wpedantic warnings about constructs used in MFC, such as implicitint and getting a pointer to member function via non-standard syntax.

-fnew-inheriting-ctors

Enable the P0136 adjustment to the semantics of C++11 constructorinheritance. This is part of C++17 but also considered to be a DefectReport against C++11 and C++14. This flag is enabled by defaultunless-fabi-version=10 or lower is specified.

-fnew-ttp-matching

Enable the P0522 resolution to Core issue 150, template templateparameters and default arguments: this allows a template with defaulttemplate arguments as an argument for a template template parameterwith fewer template parameters. This flag is enabled by default for-std=c++17.

-fno-nonansi-builtins

Disable built-in declarations of functions that are not mandated byANSI/ISO C. These includeffs,alloca,_exit,index,bzero,conjf, and other related functions.

-fnothrow-opt

Treat athrow() exception specification as if it were anoexcept specification to reduce or eliminate the text sizeoverhead relative to a function with no exception specification. Ifthe function has local variables of types with non-trivialdestructors, the exception specification actually makes thefunction smaller because the EH cleanups for those variables can beoptimized away. The semantic effect is that an exception thrown out ofa function with such an exception specification results in a calltoterminate rather thanunexpected.

-fno-operator-names

Do not treat the operator name keywordsand,bitand,bitor,compl,not,or andxor assynonyms as keywords.

-fno-optional-diags

Disable diagnostics that the standard says a compiler does not need toissue. Currently, the only such diagnostic issued by G++ is the one fora name having multiple meanings within a class.

-fno-pretty-templates

When an error message refers to a specialization of a functiontemplate, the compiler normally prints the signature of thetemplate followed by the template arguments and any typedefs ortypenames in the signature (e.g.void f(T) [with T = int]rather thanvoid f(int)) so that it’s clear which template isinvolved. When an error message refers to a specialization of a classtemplate, the compiler omits any template arguments that matchthe default template arguments for that template. If either of thesebehaviors make it harder to understand the error message rather thaneasier, you can use-fno-pretty-templates to disable them.

-frange-for-ext-temps

Enable lifetime extension of C++ range based for temporaries.With-std=c++23 and above this is part of the language standard,so lifetime of the temporaries is extended until the end of the loopby default. This option allows enabling that behavior alsoin earlier versions of the standard.

-fno-rtti

Disable generation of information about every class with virtualfunctions for use by the C++ run-time type identification features(dynamic_cast andtypeid). If you don’t use those partsof the language, you can save some space by using this flag. Note thatexception handling uses the same information, but G++ generates it asneeded. Thedynamic_cast operator can still be used for casts thatdo not require run-time type information, i.e. casts tovoid * or tounambiguous base classes.

Mixing code compiled with-frtti with that compiled with-fno-rtti may not work. For example, programs mayfail to link if a class compiled with-fno-rtti is used as a basefor a class compiled with-frtti.

-fsized-deallocation

Enable the built-in global declarations

void operator delete (void *, std::size_t) noexcept;void operator delete[] (void *, std::size_t) noexcept;

as introduced in C++14. This is useful for user-defined replacementdeallocation functions that, for example, use the size of the objectto make deallocation faster. Enabled by default under-std=c++14 and above. The flag-Wsized-deallocationwarns about places that might want to add a definition.

-fstrict-enums

Allow the compiler to optimize using the assumption that a value ofenumerated type can only be one of the values of the enumeration (asdefined in the C++ standard; basically, a value that can berepresented in the minimum number of bits needed to represent all theenumerators). This assumption may not be valid if the program uses acast to convert an arbitrary integer value to the enumerated type.This option has no effect for an enumeration type with a fixed underlyingtype.

-fstrong-eval-order
-fstrong-eval-order=kind

Evaluate member access, array subscripting, and shift expressions inleft-to-right order, and evaluate assignment in right-to-left order,as adopted for C++17.-fstrong-eval-order is equivalent to-fstrong-eval-order=all,and is enabled by default with-std=c++17 or later.

-fstrong-eval-order=some enables just the ordering of memberaccess and shift expressions, and is the default for C++ dialects prior toC++17.

-fstrong-eval-order=none is equivalent to-fno-strong-eval-order.

-ftemplate-backtrace-limit=n

Set the maximum number of template instantiation notes for a singlewarning or error ton. The default value is 10.

-ftemplate-depth=n

Set the maximum instantiation depth for template classes ton.A limit on the template instantiation depth is needed to detectendless recursions during template class instantiation. ANSI/ISO C++conforming programs must not rely on a maximum depth greater than 17(changed to 1024 in C++11). The default value is 900, as the compilercan run out of stack space before hitting 1024 in some situations.

-fno-threadsafe-statics

Do not emit the extra code to use the routines specified in the C++ABI for thread-safe initialization of local statics. You can use thisoption to reduce code size slightly in code that doesn’t need to bethread-safe.

-fuse-cxa-atexit

Register destructors for objects with static storage duration with the__cxa_atexit function rather than theatexit function.This option is required for fully standards-compliant handling of staticdestructors, but only works if your C library supports__cxa_atexit.

-fno-use-cxa-get-exception-ptr

Don’t use the__cxa_get_exception_ptr runtime routine. Thiscausesstd::uncaught_exception to be incorrect, but is necessaryif the runtime routine is not available.

-fvisibility-inlines-hidden

This switch declares that the user does not attempt to comparepointers to inline functions or methods where the addresses of the two functionsare taken in different shared objects.

The effect of this is that GCC may, effectively, mark inline methods with__attribute__ ((visibility ("hidden"))) so that they do notappear in the export table of a DSO and do not require a PLT indirectionwhen used within the DSO. Enabling this option can have a dramatic effecton load and link times of a DSO as it massively reduces the size of thedynamic export table when the library makes heavy use of templates.

The behavior of this switch is not quite the same as marking themethods as hidden directly, because it does not affect static variableslocal to the function or cause the compiler to deduce thatthe function is defined in only one shared object.

You may mark a method as having a visibility explicitly to negate theeffect of the switch for that method. For example, if you do want tocompare pointers to a particular inline method, you might mark it ashaving default visibility. Marking the enclosing class with explicitvisibility has no effect.

Explicitly instantiated inline methods are unaffected by this optionas their linkage might otherwise cross a shared library boundary.SeeWhere’s the Template?.

-fvisibility-ms-compat

This flag attempts to use visibility settings to make GCC’s C++linkage model compatible with that of Microsoft Visual Studio.

The flag makes these changes to GCC’s linkage model:

  1. It sets the default visibility tohidden, like-fvisibility=hidden.
  2. Types, but not their members, are not hidden by default.
  3. The One Definition Rule is relaxed for types without explicitvisibility specifications that are defined in more than oneshared object: those declarations are permitted if they arepermitted when this option is not used.

In new code it is better to use-fvisibility=hidden andexport those classes that are intended to be externally visible.Unfortunately it is possible for code to rely, perhaps accidentally,on the Visual Studio behavior.

Among the consequences of these changes are that static data membersof the same type with the same name but defined in different sharedobjects are different, so changing one does not change the other;and that pointers to function members defined in different sharedobjects may not compare equal. When this flag is given, it is aviolation of the ODR to define types with the same name differently.

-fno-weak

Do not use weak symbol support, even if it is provided by the linker.By default, G++ uses weak symbols if they are available. Thisoption exists only for testing, and should not be used by end-users;it results in inferior code and has no benefits. This option maybe removed in a future release of G++.

-fext-numeric-literals(C++ and Objective-C++ only)

Accept imaginary, fixed-point, or machine-definedliteral number suffixes as GNU extensions.When this option is turned off these suffixes are treatedas C++11 user-defined literal numeric suffixes.This is on by default for all pre-C++11 dialects and all GNU dialects:-std=c++98,-std=gnu++98,-std=gnu++11,-std=gnu++14.This option is off by defaultfor ISO C++11 onwards (-std=c++11, ...).

-nostdinc++

Do not search for header files in the standard directories specific toC++, but do still search the other standard directories. (This optionis used when building the C++ library.)

-flang-info-include-translate
-flang-info-include-translate-not
-flang-info-include-translate=header

Inform of include translation events. The first will note acceptedinclude translations, the second will note declined includetranslations. Theheader form will inform of includetranslations relating to that specific header. Ifheader is ofthe form"user" or<system> it will be resolved to aspecific user or system header using the include path.

-flang-info-module-cmi
-flang-info-module-cmi=module

Inform of Compiled Module Interface pathnames. The first will noteall read CMI pathnames. Themodule form will not reading aspecific module’s CMI.module may be a named module or aheader-unit (the latter indicated by either being a pathname containingdirectory separators or enclosed in<> or"").

-stdlib=libstdc++,libc++

When G++ is configured to support this option, it allows specification ofalternate C++ runtime libraries. Two options are available:libstdc++(the default, native C++ runtime for G++) andlibc++ which is theC++ runtime installed on some operating systems (e.g. Darwin versions fromDarwin11 onwards). The option switches G++ to use the headers from thespecified library and to emit-lstdc++ or-lc++ respectively,when a C++ runtime is required for linking.

In addition, these warning options have meanings only for C++ programs:

-Wabi-tag(C++ and Objective-C++ only)

Warn when a type with an ABI tag is used in a context that does nothave that ABI tag. SeeC++-Specific Variable, Function, and Type Attributes for more informationabout ABI tags.

-Wno-abbreviated-auto-in-template-arg

Disable the error for anauto placeholder type used within atemplate argument list to declare a C++20 abbreviated functiontemplate, e.g.

void f(S<auto>);

This feature was proposed in the Concepts TS, but was not adopted intoC++20; in the standard, a placeholder in a parameter declaration mustappear as a decl-specifier. The error can also be reduced to awarning by-fpermissive or-Wno-error=abbreviated-auto-in-template-arg.

-Wcomma-subscript(C++ and Objective-C++ only)

Warn about uses of a comma expression within a subscripting expression.This usage was deprecated in C++20 and is going to be removed in C++23.However, a comma expression wrapped in( ) is not deprecated. Example:

void f(int *a, int b, int c) {    a[b,c];     // deprecated in C++20, invalid in C++23    a[(b,c)];   // OK}

In C++23 it is valid to have comma separated expressions in a subscriptwhen an overloaded subscript operator is found and supports the rightnumber and types of arguments. G++ will accept the formerly valid syntaxfor code that is not valid in C++23 but used to be valid but deprecatedin C++20 with a pedantic warning that can be disabled with-Wno-comma-subscript.

Enabled by default with-std=c++20 unless-Wno-deprecated, and after-std=c++23 regardless of-Wno-deprecated. Before-std=c++20, enabled withexplicit-Wdeprecated.

This warning is upgraded to an error by-pedantic-errors inC++23 mode or later.

-Wctad-maybe-unsupported(C++ and Objective-C++ only)

Warn when performing class template argument deduction (CTAD) on a type withno explicitly written deduction guides. This warning will point out caseswhere CTAD succeeded only because the compiler synthesized the implicitdeduction guides, which might not be what the programmer intended. Certainstyle guides allow CTAD only on types that specifically "opt-in"; i.e., ontypes that are designed to support CTAD. This warning can be suppressed withthe following pattern:

struct allow_ctad_t; // any name workstemplate <typename T> struct S {  S(T) { }};// Guide with incomplete parameter type will never be considered.S(allow_ctad_t) -> S<void>;
-Wctor-dtor-privacy(C++ and Objective-C++ only)

Warn when a class seems unusable because all the constructors ordestructors in that class are private, and it has neither friends norpublic static member functions. Also warn if there are no non-privatemethods, and there’s at least one private member function that isn’ta constructor or destructor.

-Wdangling-reference(C++ and Objective-C++ only)

Warn when a reference is bound to a temporary whose lifetime has ended.For example:

int n = 1;const int& r = std::max(n - 1, n + 1); // r is dangling

In the example above, two temporaries are created, one for eachargument, and a reference to one of the temporaries is returned.However, both temporaries are destroyed at the end of the fullexpression, so the referencer is dangling. This warningalso detects dangling references in member initializer lists:

const int& f(const int& i) { return i; }struct S {  const int &r; // r is dangling  S() : r(f(10)) { }};

Member functions are checked as well, but only their object argument:

struct S {   const S& self () { return *this; }};const S& s = S().self(); // s is dangling

Certain functions are safe in this respect, for examplestd::use_facet:they take and return a reference, but they don’t return one of its arguments,which can fool the warning. Such functions can be excluded from the warningby wrapping them in a#pragma:

#pragma GCC diagnostic push#pragma GCC diagnostic ignored "-Wdangling-reference"const T& foo (const T&) { … }#pragma GCC diagnostic pop

The#pragma can also surround the class; in that case, the warningwill be disabled for all the member functions.

-Wdangling-reference also warns about code like

auto p = std::minmax(1, 2);

wherestd::minmax returnsstd::pair<const int&, const int&>, andboth references dangle after the end of the full expression that containsthe call tostd::minmax.

The warning does not warn forstd::span-like classes. We considerclasses of the form:

template<typename T>struct Span {  T* data_;  std::size len_;};

asstd::span-like; that is, the class is a non-union classthat has a pointer data member and a trivial destructor.

The warning can be disabled by using thegnu::no_dangling attribute(seeC++-Specific Variable, Function, and Type Attributes).

This warning is enabled by-Wextra.

-Wdelete-non-virtual-dtor(C++ and Objective-C++ only)

Warn whendelete is used to destroy an instance of a class thathas virtual functions and non-virtual destructor. It is unsafe to deletean instance of a derived class through a pointer to a base class if thebase class does not have a virtual destructor. This warning is enabledby-Wall.

-Wdeprecated-copy(C++ and Objective-C++ only)

Warn that the implicit declaration of a copy constructor or copyassignment operator is deprecated if the class has a user-providedcopy constructor or copy assignment operator, in C++11 and up. Thiswarning is enabled by-Wextra.

-Wdeprecated-copy-dtor(C++ and Objective-C++ only)

Similar to-Wdeprecated-copy, but also deprecate if the class has auser-provided destructor.

-Wno-deprecated-enum-enum-conversion(C++ and Objective-C++ only)

Disable the warning about the case when the usual arithmetic conversionsare applied on operands where one is of enumeration type and the other isof a different enumeration type. This conversion was deprecated in C++20.For example:

enum E1 { e };enum E2 { f };int k = f - e;

-Wdeprecated-enum-enum-conversion is enabled by default with-std=c++20. In pre-C++20 dialects, this warning can be enabledby-Wenum-conversion or-Wdeprecated.

-Wno-deprecated-enum-float-conversion(C++ and Objective-C++ only)

Disable the warning about the case when the usual arithmetic conversionsare applied on operands where one is of enumeration type and the other isof a floating-point type. This conversion was deprecated in C++20. Forexample:

enum E1 { e };enum E2 { f };bool b = e <= 3.7;

-Wdeprecated-enum-float-conversion is enabled by default with-std=c++20. In pre-C++20 dialects, this warning can be enabledby-Wenum-conversion or-Wdeprecated.

-Wdeprecated-literal-operator(C++ and Objective-C++ only)

Warn that the declaration of a user-defined literal operator with aspace before the suffix is deprecated. This warning is enabled bydefault in C++23, or with explicit-Wdeprecated.

string operator "" _i18n(const char*, std::size_t); // deprecatedstring operator ""_i18n(const char*, std::size_t); // preferred
-Wdeprecated-variadic-comma-omission(C++ and Objective-C++ only)

Warn that omitting a comma before the varargs... at the end ofa function parameter list is deprecated. This warning is enabled bydefault in C++26, or with explicit-Wdeprecated.

void f1(int...); // deprecatedvoid f1(int, ...); // preferredtemplate <typename ...T>void f2(T...); // oktemplate <typename ...T>void f3(T......); // deprecated
-Wno-elaborated-enum-base

For C++11 and above, warn if an (invalid) additional enum-base is usedin an elaborated-type-specifier. That is, if an enum with givenunderlying type and no enumerator list is used in a declaration otherthan just a standalone declaration of the enum. Enabled by default. Thiswarning is upgraded to an error with -pedantic-errors.

-Wno-init-list-lifetime(C++ and Objective-C++ only)

Do not warn about uses ofstd::initializer_list that are likelyto result in dangling pointers. Since the underlying array for aninitializer_list is handled like a normal C++ temporary object,it is easy to inadvertently keep a pointer to the array past the endof the array’s lifetime. For example:

  • If a function returns a temporaryinitializer_list, or a localinitializer_list variable, the array’s lifetime ends at the endof the return statement, so the value returned has a dangling pointer.
  • If a new-expression creates aninitializer_list, the array onlylives until the end of the enclosing full-expression, so theinitializer_list in the heap has a dangling pointer.
  • When aninitializer_list variable is assigned from abrace-enclosed initializer list, the temporary array created for theright side of the assignment only lives until the end of thefull-expression, so at the next statement theinitializer_listvariable has a dangling pointer.
    // li's initial underlying array lives as long as listd::initializer_list<int> li = { 1,2,3 };// assignment changes li to point to a temporary arrayli = { 4, 5 };// now the temporary is gone and li has a dangling pointerint i = li.begin()[0] // undefined behavior
  • When a list constructor stores thebegin pointer from theinitializer_list argument, this doesn’t extend the lifetime ofthe array, so if a class variable is constructed from a temporaryinitializer_list, the pointer is left dangling by the end ofthe variable declaration statement.
-Winvalid-constexpr

Warn when a function never produces a constant expression. In C++20and earlier, for everyconstexpr function and function template,there must be at least one set of function arguments in at least oneinstantiation such that an invocation of the function or constructorcould be an evaluated subexpression of a core constant expression.C++23 removed this restriction, so it’s possible to have a functionor a function template markedconstexpr for which no invocationsatisfies the requirements of a core constant expression.

This warning is enabled as a pedantic warning by default in C++20 andearlier. In C++23,-Winvalid-constexpr can be turned on, inwhich case it will be an ordinary warning. For example:

void f (int& i);constexpr voidg (int& i){  // Warns by default in C++20, in C++23 only with -Winvalid-constexpr.  f(i);}
-Winvalid-imported-macros

Verify all imported macro definitions are valid at the end ofcompilation. This is not enabled by default, as it requiresadditional processing to determine. It may be useful when preparingsets of header-units to ensure consistent macros.

-Wno-literal-suffix(C++ and Objective-C++ only)

Do not warn when a string or character literal is followed by aud-suffix which does not begin with an underscore. As a conformingextension, GCC treats such suffixes as separate preprocessing tokensin order to maintain backwards compatibility with code that usesformatting macros from<inttypes.h>. For example:

#define __STDC_FORMAT_MACROS#include <inttypes.h>#include <stdio.h>int main() {  int64_t i64 = 123;  printf("My int64: %" PRId64"\n", i64);}

In this case,PRId64 is treated as a separate preprocessing token.

This option also controls warnings when a user-defined literaloperator is declared with a literal suffix identifier that doesn’tbegin with an underscore. Literal suffix identifiers that don’t beginwith an underscore are reserved for future standardization.

These warnings are enabled by default.

-Wno-narrowing(C++ and Objective-C++ only)

For C++11 and later standards, narrowing conversions are diagnosed by default,as required by the standard. A narrowing conversion from a constant producesan error, and a narrowing conversion from a non-constant produces a warning,but-Wno-narrowing suppresses the diagnostic.Note that this does not affect the meaning of well-formed code;narrowing conversions are still considered ill-formed in SFINAE contexts.

With-Wnarrowing in C++98, warn when a narrowingconversion prohibited by C++11 occurs within‘{ }’, e.g.

int i = { 2.2 }; // error: narrowing from double to int

This flag is included in-Wall and-Wc++11-compat.

-Wnoexcept(C++ and Objective-C++ only)

Warn when a noexcept-expression evaluates to false because of a callto a function that does not have a non-throwing exceptionspecification (i.e.throw() ornoexcept) but is known bythe compiler to never throw an exception.

-Wnoexcept-type(C++ and Objective-C++ only)

Warn if the C++17 feature makingnoexcept part of a functiontype changes the mangled name of a symbol relative to C++14. Enabledby-Wabi and-Wc++17-compat.

As an example:

template <class T> void f(T t) { t(); };void g() noexcept;void h() { f(g); }

In C++14,f callsf<void(*)()>, but inC++17 it callsf<void(*)()noexcept>.

-Wclass-memaccess(C++ and Objective-C++ only)

Warn when the destination of a call to a raw memory function such asmemset ormemcpy is an object of class type, and when writinginto such an object might bypass the class non-trivial or deleted constructoror copy assignment, violate const-correctness or encapsulation, or corruptvirtual table pointers. Modifying the representation of such objects mayviolate invariants maintained by member functions of the class. For example,the call tomemset below is undefined because it modifies a non-trivialclass object and is, therefore, diagnosed. The safe way to either initializeor clear the storage of objects of such types is by using the appropriateconstructor or assignment operator, if one is available.

std::string str = "abc";memset (&str, 0, sizeof str);

The-Wclass-memaccess option is enabled by-Wall.Explicitly casting the pointer to the class object tovoid * orto a type that can be safely accessed by the raw memory function suppressesthe warning.

-Wnon-virtual-dtor(C++ and Objective-C++ only)

Warn when a class has virtual functions and an accessible non-virtualdestructor itself or in an accessible polymorphic base class, in whichcase it is possible but unsafe to delete an instance of a derivedclass through a pointer to the class itself or base class. Thiswarning is automatically enabled if-Weffc++ is specified.The-Wdelete-non-virtual-dtor option (enabled by-Wall)should be preferred because it warns about the unsafe cases without falsepositives.

-Wregister(C++ and Objective-C++ only)

Warn on uses of theregister storage class specifier, exceptwhen it is part of the GNUVariables in Specified Registers extension.The use of theregister keyword as storage class specifier hasbeen deprecated in C++11 and removed in C++17.Enabled by default with-std=c++17.

-Wreorder(C++ and Objective-C++ only)

Warn when the order of member initializers given in the code does notmatch the order in which they must be executed. For instance:

struct A {  int i;  int j;  A(): j (0), i (1) { }};

The compiler rearranges the member initializers foriandj to match the declaration order of the members, emittinga warning to that effect. This warning is enabled by-Wall.

-Wno-pessimizing-move(C++ and Objective-C++ only)

This warning warns when a call tostd::move prevents copyelision. A typical scenario when copy elision can occur is when returning ina function with a class return type, when the expression being returned is thename of a non-volatile automatic object, and is not a function parameter, andhas the same type as the function return type.

struct T {…};T fn(){  T t;  …  return std::move (t);}

But in this example, thestd::move call prevents copy elision.

This warning is enabled by-Wall.

-Wno-redundant-move(C++ and Objective-C++ only)

This warning warns about redundant calls tostd::move; that is, whena move operation would have been performed even without thestd::movecall. This happens because the compiler is forced to treat the object as ifit were an rvalue in certain situations such as returning a local variable,where copy elision isn’t applicable. Consider:

struct T {…};T fn(T t){  …  return std::move (t);}

Here, thestd::move call is redundant. Because G++ implements CoreIssue 1579, another example is:

struct T { // convertible to U…};struct U {…};U fn(){  T t;  …  return std::move (t);}

In this example, copy elision isn’t applicable because the type of theexpression being returned and the function return type differ, yet G++treats the return value as if it were designated by an rvalue.

This warning is enabled by-Wextra.

-Wrange-loop-construct(C++ and Objective-C++ only)

This warning warns when a C++ range-based for-loop is creating an unnecessarycopy. This can happen when the range declaration is not a reference, butprobably should be. For example:

struct S { char arr[128]; };void fn () {  S arr[5];  for (const auto x : arr) { … }}

It does not warn when the type being copied is a trivially-copyable type whosesize is less than 64 bytes.

This warning also warns when a loop variable in a range-based for-loop isinitialized with a value of a different type resulting in a copy. For example:

void fn() {  int arr[10];  for (const double &x : arr) { … }}

In the example above, in every iteration of the loop a temporary value oftypedouble is created and destroyed, to which the referenceconst double & is bound.

This warning is enabled by-Wall.

-Wredundant-tags(C++ and Objective-C++ only)

Warn about redundant class-key and enum-key in references to class typesand enumerated types in contexts where the key can be eliminated withoutcausing an ambiguity. For example:

struct foo;struct foo *p;   // warn that keyword struct can be eliminated

On the other hand, in this example there is no warning:

struct foo;void foo ();   // "hides" struct foovoid bar (struct foo&);  // no warning, keyword struct is necessary
-Wno-subobject-linkage(C++ and Objective-C++ only)

Do not warnif a class type has a base or a field whose type uses the anonymousnamespace or depends on a type with no linkage. If a type A depends ona type B with no or internal linkage, defining it in multipletranslation units would be an ODR violation because the meaning of Bis different in each translation unit. If A only appears in a singletranslation unit, the best way to silence the warning is to give itinternal linkage by putting it in an anonymous namespace as well. Thecompiler doesn’t give this warning for types defined in the main .Cfile, as those are unlikely to have multiple definitions.-Wsubobject-linkage is enabled by default.

-Weffc++(C++ and Objective-C++ only)

Warn about violations of the following style guidelines from Scott Meyers’Effective C++ series of books:

  • Define a copy constructor and an assignment operator for classeswith dynamically-allocated memory.
  • Prefer initialization to assignment in constructors.
  • Haveoperator= return a reference to*this.
  • Don’t try to return a reference when you must return an object.
  • Distinguish between prefix and postfix forms of increment anddecrement operators.
  • Never overload&&,||, or,.

This option also enables-Wnon-virtual-dtor, which is alsoone of the effective C++ recommendations. However, the check isextended to warn about the lack of virtual destructor in accessiblenon-polymorphic bases classes too.

When selecting this option, be aware that the standard libraryheaders do not obey all of these guidelines; use ‘grep -v’to filter out those warnings.

-Wno-exceptions(C++ and Objective-C++ only)

Disable the warning about the case when an exception handler is shadowed byanother handler, which can point out a wrong ordering of exception handlers.

Warn about a class that is found to be incomplete, or a function withauto return type that has not yet been deduced, in a context wherethat causes substitution failure rather than an error, and then theclass or function is defined later in the translation unit. This isproblematic because template instantiations or concept checks couldhave different results if they first occur either before or after thedefinition.

This warning is enabled by default.-Wsfinae-incomplete=2adds a warning at the point of substitution failure, to make it easierto track down problems flagged by the default mode.

-Wstrict-null-sentinel(C++ and Objective-C++ only)

Warn about the use of an uncastedNULL as sentinel. Whencompiling only with GCC this is a valid sentinel, asNULL is definedto__null. Although it is a null pointer constant rather than anull pointer, it is guaranteed to be of the same size as a pointer.But this use is not portable across different compilers.

-Wno-non-c-typedef-for-linkage(C++ and Objective-C++ only)

Disable pedwarn for unnamed classes with a typedef name for linkage purposescontaining C++ specific members, base classes, default member initializersor lambda expressions, including those on nested member classes.

typedef struct {  int a; // non-static data members are ok  struct T { int b; }; // member classes too  enum E { E1, E2, E3 }; // member enumerations as well  int c = 42; // default member initializers are not ok  struct U : A { int c; }; // classes with base classes are not ok  typedef int V; // typedef is not ok  using W = int; // using declaration is not ok  decltype([](){}) x; // lambda expressions not ok} S;

In all these cases, the tag name S should be added after the struct keyword.

-Wno-non-template-friend(C++ and Objective-C++ only)

Disable warnings when non-template friend functions are declaredwithin a template. In very old versions of GCC that predate implementationof the ISO standard, declarations such as‘friend int foo(int)’, where the name of the friend is an unqualified-id,could be interpreted as a particular specialization of a templatefunction; the warning exists to diagnose compatibility problems,and is enabled by default.

-Wold-style-cast(C++ and Objective-C++ only)

Warn if an old-style (C-style) cast to a non-void type is used withina C++ program. The new-style casts (dynamic_cast,static_cast,reinterpret_cast, andconst_cast) areless vulnerable to unintended effects and much easier to search for.

-Woverloaded-virtual(C++ and Objective-C++ only)
-Woverloaded-virtual=n

Warn when a function declaration hides virtual functions from abase class. For example, in:

struct A {  virtual void f();};struct B: public A {  void f(int); // does not override};

theA class version off is hidden inB, and codelike:

B* b;b->f();

fails to compile.

In cases where the different signatures are not an accident, thesimplest solution is to add a using-declaration to the derived classto un-hide the base function, e.g. addusing A::f; toB.

The optional level suffix controls the behavior when all thedeclarations in the derived class override virtual functions in thebase class, even if not all of the base functions are overridden:

struct C {  virtual void f();  virtual void f(int);};struct D: public C {  void f(int); // does override}

This pattern is less likely to be a mistake; if D is only usedvirtually, the user might have decided that the base class semanticsfor some of the overloads are fine.

At level 1, this case does not warn; at level 2, it does.-Woverloaded-virtual by itself selects level 2. Level 1 isincluded in-Wall.

-Wno-pmf-conversions(C++ and Objective-C++ only)

Disable the diagnostic for converting a bound pointer to member functionto a plain pointer.

-Wsign-promo(C++ and Objective-C++ only)

Warn when overload resolution chooses a promotion from unsigned orenumerated type to a signed type, over a conversion to an unsigned type ofthe same size. Previous versions of G++ tried to preserveunsignedness, but the standard mandates the current behavior.

-Wtemplates(C++ and Objective-C++ only)

Warn when a primary template declaration is encountered. Some codingrules disallow templates, and this may be used to enforce that rule.The warning is inactive inside a system header file, such as the STL, soone can still use the STL. One may also instantiate or specializetemplates.

-Wmismatched-new-delete(C++ and Objective-C++ only)

Warn for mismatches between calls tooperator new oroperatordelete and the corresponding call to the allocation or deallocation function.This includes invocations of C++operator delete with pointersreturned from either mismatched forms ofoperator new, or from otherfunctions that allocate objects for which theoperator delete isn’ta suitable deallocator, as well as calls to other deallocation functionswith pointers returned fromoperator new for which the deallocationfunction isn’t suitable.

For example, thedelete expression in the function below is diagnosedbecause it doesn’t match the array form of thenew expressionthe pointer argument was returned from. Similarly, the call tofreeis also diagnosed.

void f (){  int *a = new int[n];  delete a;   // warning: mismatch in array forms of expressions  char *p = new char[n];  free (p);   // warning: mismatch between new and free}

The related option-Wmismatched-dealloc diagnoses mismatchesinvolving allocation and deallocation functions other thanoperatornew andoperator delete.

-Wmismatched-new-delete is included in-Wall.

-Wmismatched-tags(C++ and Objective-C++ only)

Warn for declarations of structs, classes, and class templates and theirspecializations with a class-key that does not match either the definitionor the first declaration if no definition is provided.

For example, the declaration ofstruct Object in the argument listofdraw triggers the warning. To avoid it, either remove the redundantclass-keystruct or replace it withclass to match its definition.

class Object {public:  virtual ~Object () = 0;};void draw (struct Object*);

It is not wrong to declare a class with the class-keystruct asthe example above shows. The-Wmismatched-tags option is intendedto help achieve a consistent style of class declarations. In code that isintended to be portable to Windows-based compilers the warning helps preventunresolved references due to the difference in the mangling of symbolsdeclared with different class-keys. The option can be used either on itsown or in conjunction with-Wredundant-tags.

-Wmultiple-inheritance(C++ and Objective-C++ only)

Warn when a class is defined with multiple direct base classes. Somecoding rules disallow multiple inheritance, and this may be used toenforce that rule. The warning is inactive inside a system header file,such as the STL, so one can still use the STL. One may also defineclasses that indirectly use multiple inheritance.

-Wvirtual-inheritance

Warn when a class is defined with a virtual direct base class. Somecoding rules disallow multiple inheritance, and this may be used toenforce that rule. The warning is inactive inside a system header file,such as the STL, so one can still use the STL. One may also defineclasses that indirectly use virtual inheritance.

-Wno-virtual-move-assign

Suppress warnings about inheriting from a virtual base with anon-trivial C++11 move assignment operator. This is dangerous becauseif the virtual base is reachable along more than one path, it ismoved multiple times, which can mean both objects end up in themoved-from state. If the move assignment operator is written to avoidmoving from a moved-from object, this warning can be disabled.

-Wnamespaces

Warn when a namespace definition is opened. Some coding rules disallownamespaces, and this may be used to enforce that rule. The warning isinactive inside a system header file, such as the STL, so one can stilluse the STL. One may also use using directives and qualified names.

-Wno-template-body(C++ and Objective-C++ only)

Disable diagnosing errors when parsing a template, and instead issue anerror only upon instantiation of the template. This flag can also beused to downgrade such errors into warnings withWno-error= or-fpermissive.

-Wno-template-id-cdtor(C++ and Objective-C++ only)

Disable the warning about the use of simple-template-id as the declarator-idof a constructor or destructor, which became invalid in C++20 via DR 2237.For example:

template<typename T> struct S {  S<T>(); // should be S();  ~S<T>();  // should be ~S();};

-Wtemplate-id-cdtor is enabled by default with-std=c++20; it is also enabled by-Wc++20-compat.

-Wtemplate-names-tu-local

Warn when a template body hides an exposure of a translation-unit-localentity. In most cases, referring to a translation-unit-local entity(such as an internal linkage declaration) within an entity that isemitted into a module’s CMI is an error. However, within theinitializer of a variable, or in the body of a non-inline function,this is not an exposure and no error is emitted.

This can cause variable or function templates to accidentally becomeunusable if they reference such an entity, because other translationunits that import the template will never be able to instantiate it.This warning attempts to detect cases where this might occur.The presence of an explicit instantiation silences the warning.

This flag is enabled by-Wextra.

-Wno-expose-global-module-tu-local

An exposure of a translation-unit-local entity from a module interface isinvalid, as this may cause ODR violations and manifest in link errors or otherunexpected behaviour. However, many existing libraries declare TU-localentities in their interface, and avoiding exposures of these entities may bedifficult in some cases.

As an extension, GCC allows exposures of internal variables and functions thatwere declared in the global module fragment. This warning indicates when suchan invalid exposure has occurred, and can be silenced using diagnostic pragmaseither at the site of the exposure, or at the point of declaration of theinternal declaration.

When combined with-Wtemplate-names-tu-local, GCC will also warn aboutnon-exposure references to TU-local entities in template bodies. Such templatescan still be instantiated in other TUs but the above risks regarding exposuresof translation-unit-local entities apply.

This warning is enabled by default, and is upgraded to an error by-pedantic-errors.

-Wno-external-tu-local

Warn when naming a TU-local entity outside of the translation unit itwas declared in. Such declarations will be ignored during name lookup.This can occur when performing ADL from a template declared in the sameTU as the internal function:

export module M;template <typename T> void foo(T t) {  bar(t);}struct S {} s;static void bar(S) {}  // internal linkage// instantiating foo(s) from outside this TU can see ::bar,// but naming it there is ill-formed.

This can be worked around by makingbar attached to the globalmodule, usingextern "C++".

This warning is enabled by default, and is upgraded to an error by-pedantic-errors.

-Wno-terminate(C++ and Objective-C++ only)

Disable the warning about a throw-expression that will immediatelyresult in a call toterminate.

-Wno-vexing-parse(C++ and Objective-C++ only)

Warn about the most vexing parse syntactic ambiguity. This warns aboutthe cases when a declaration looks like a variable definition, but theC++ language requires it to be interpreted as a function declaration.For instance:

void f(double a) {  int i();        // extern int i (void);  int n(int(a));  // extern int n (int);}

Another example:

struct S { S(int); };void f(double a) {  S x(int(a));   // extern struct S x (int);  S y(int());    // extern struct S y (int (*) (void));  S z();         // extern struct S z (void);}

The warning will suggest options how to deal with such an ambiguity; e.g.,it can suggest removing the parentheses or using braces instead.

This warning is enabled by default.

-Wno-class-conversion(C++ and Objective-C++ only)

Do not warn when a conversion function converts anobject to the same type, to a base class of that type, or to void; sucha conversion function will never be called.

-Wvolatile(C++ and Objective-C++ only)

Warn about deprecated uses of thevolatile qualifier. This includespostfix and prefix++ and-- expressions ofvolatile-qualified types, using simple assignments where the leftoperand is avolatile-qualified non-class type for their value,compound assignments where the left operand is avolatile-qualifiednon-class type,volatile-qualified function return type,volatile-qualified parameter type, and structured bindings of avolatile-qualified type. This usage was deprecated in C++20.

Enabled by default with-std=c++20. Before-std=c++20, enabled with explicit-Wdeprecated.

-Waligned-new
-Waligned-new=[none|global|all]

Warn about a new-expression of a type that requires greater alignmentthan thealignof(std::max_align_t) but uses an allocationfunction without an explicit alignment parameter. This option isenabled by-Wall.

Normally this only warns about global allocation functions, but-Waligned-new=all also warns about class member allocationfunctions.

-Wno-placement-new
-Wplacement-new=n

Warn about placement new expressions with undefined behavior, such asconstructing an object in a buffer that is smaller than the type ofthe object. For example, the placement new expression below is diagnosedbecause it attempts to construct an array of 64 integers in a buffer only64 bytes large.

char buf [64];new (buf) int[64];

This warning is enabled by default.

-Wplacement-new=1

This is the default warning level of-Wplacement-new. At thislevel the warning is not issued for some strictly undefined constructs thatGCC allows as extensions for compatibility with legacy code. For example,the followingnew expression is not diagnosed at this level eventhough it has undefined behavior according to the C++ standard becauseit writes past the end of the one-element array.

struct S { int n, a[1]; };S *s = (S *)malloc (sizeof *s + 31 * sizeof s->a[0]);new (s->a)int [32]();
-Wplacement-new=2

At this level, in addition to diagnosing all the same constructs as at level1, a diagnostic is also issued for placement new expressions that constructan object in the last member of structure whose type is an array of a singleelement and whose size is less than the size of the object being constructed.While the previous example would be diagnosed, the following construct makesuse of the flexible member array extension to avoid the warning at level 2.

struct S { int n, a[]; };S *s = (S *)malloc (sizeof *s + 32 * sizeof s->a[0]);new (s->a)int [32]();
-Wcatch-value
-Wcatch-value=n(C++ and Objective-C++ only)

Warn about catch handlers that do not catch via reference.With-Wcatch-value=1 (or-Wcatch-value for short)warn about polymorphic class types that are caught by value.With-Wcatch-value=2 warn about all class types that are caughtby value. With-Wcatch-value=3 warn about all types that arenot caught by reference.-Wcatch-value is enabled by-Wall.

-Wconditionally-supported(C++ and Objective-C++ only)

Warn for conditionally-supported (C++11 [intro.defs]) constructs.

-Wno-defaulted-function-deleted(C++ and Objective-C++ only)

Warn when an explicitly defaulted function is deleted by the compiler.That can occur when the function’s declared type does not match the typeof the function that would have been implicitly declared. This warningis enabled by default.

-Wno-delete-incomplete(C++ and Objective-C++ only)

Do not warn when deleting a pointer to incomplete type, which may causeundefined behavior at runtime. This warning is enabled by default.

-Wextra-semi(C++, Objective-C++ only)

Warn about redundant semicolons. There are various contexts in which an extrasemicolon can occur. One is a semicolon after in-class function definitions,which is valid in all C++ dialects (and is never a pedwarn):

struct S {  void foo () {};};

Another is an extra semicolon at namespace scope, which has been allowedsince C++11 (therefore is a pedwarn in C++98):

struct S {};;

And yet another is an extra semicolon in class definitions, which has beenallowed since C++11 (therefore is a pedwarn in C++98):

struct S {  int a;  ;};
-Wno-global-module(C++ and Objective-C++ only)

Disable the diagnostic for when the global module fragment of a moduleunit does not consist only of preprocessor directives.

-Wno-inaccessible-base(C++, Objective-C++ only)

This option controls warningswhen a base class is inaccessible in a class derived from it due toambiguity. The warning is enabled by default.Note that the warning for ambiguous virtualbases is enabled by the-Wextra option.

struct A { int a; };struct B : A { };struct C : B, A { };
-Wno-inherited-variadic-ctor

Suppress warnings about use of C++11 inheriting constructors when thebase class inherited from has a C variadic constructor; the warning ison by default because the ellipsis is not inherited.

-Wno-invalid-offsetof(C++ and Objective-C++ only)

Suppress warnings from applying theoffsetof macro to a non-PODtype. According to the 2014 ISO C++ standard, applyingoffsetofto a non-standard-layout type is undefined. In existing C++ implementations,however,offsetof typically gives meaningful results.This flag is for users who are aware that they arewriting nonportable code and who have deliberately chosen to ignore thewarning about it.

The restrictions onoffsetof may be relaxed in a future versionof the C++ standard.

-Wsized-deallocation(C++ and Objective-C++ only)

Warn about a definition of an unsized deallocation function

void operator delete (void *) noexcept;void operator delete[] (void *) noexcept;

without a definition of the corresponding sized deallocation function

void operator delete (void *, std::size_t) noexcept;void operator delete[] (void *, std::size_t) noexcept;

or vice versa. Enabled by-Wextra along with-fsized-deallocation.

-Wsuggest-final-types

Warn about types with virtual methods where code quality would be improvedif the type were declared with the C++11final specifier,or, if possible,declared in an anonymous namespace. This allows GCC to more aggressivelydevirtualize the polymorphic calls. This warning is more effective withlink-time optimization,where the information about the class hierarchy graph ismore complete.

-Wsuggest-final-methods

Warn about virtual methods where code quality would be improved if the methodwere declared with the C++11final specifier,or, if possible, its type weredeclared in an anonymous namespace or with thefinal specifier.This warning ismore effective with link-time optimization, where the information about theclass hierarchy graph is more complete. It is recommended to first considersuggestions of-Wsuggest-final-types and then rebuild with newannotations.

-Wsuggest-override

Warn about overriding virtual functions that are not marked with theoverride keyword.

-Wno-conversion-null(C++ and Objective-C++ only)

Do not warn for conversions betweenNULL and non-pointertypes.-Wconversion-null is enabled by default.


Next:Options Controlling Objective-C and Objective-C++ Dialects, Previous:Options Controlling C Dialect, Up:GCC Command Options   [Contents][Index]


[8]ページ先頭

©2009-2025 Movatter.jp