Dead Code Elimination

Walter Bright newshound2 at digitalmars.com
Sat Oct 24 00:55:22 UTC 2026


On 10/22/2026 1:04 AM, Richard (Rikki) Andrew Cattermole wrote:
> https://learn.microsoft.com/en-us/cpp/build/reference/opt-optimizations?view=msvc-170

Quoting the manual:

REF | NOREF

/OPT:REF eliminates functions and data that are never referenced; /OPT:NOREF 
keeps functions and data that are never referenced.

When /OPT:REF is enabled, LINK removes unreferenced packaged functions and data, 
known as COMDATs. This optimization is known as transitive COMDAT elimination. 
The /OPT:REF option also disables incremental linking.

Inlined functions and member functions defined inside a class declaration are 
always COMDATs. All of the functions in an object file are made into COMDATs if 
it is compiled by using the /Gy option. To place const data in COMDATs, you must 
declare it by using __declspec(selectany). For information about how to specify 
data for removal or folding, see selectany.

By default, /OPT:REF is enabled by the linker unless /OPT:NOREF or /DEBUG is 
specified. To override this default and keep unreferenced COMDATs in the 
program, specify /OPT:NOREF. You can use the /INCLUDE option to override the 
removal of a specific symbol.

If /DEBUG is specified, the default for /OPT is NOREF, and all functions are 
preserved in the image. To override this default and optimize a debug build, 
specify /OPT:REF. This can reduce the size of your executable, and can be a 
useful optimization even in debug builds. We recommend that you also specify 
/OPT:NOICF to preserve identical functions in debug builds. This makes it easier 
to read stack traces and set breakpoints in functions that would otherwise be 
folded together.

 > For MSVC link /OPT:REF is only enabled with -release (uck).

This is incorrect. It is enabled by default, according to the manual.

BTW, there have been problems in the past with linkers that were too aggressive 
in removing unused functions and would create corrupt executables. I don't know 
the state of them today.

In any case, the compiler cannot remove them, because it does not have access to 
the rest of the program.


More information about the Digitalmars-d mailing list