How to generate warning for unreferenced local function in anonymous namespace?

2.2k views Asked by At

When using Visual C++ 2012 to compile the follow code:

namespace
{
    void unusedFunction1()
    {
    }
}

static void unusedFunction2()
{
}

With /Wall, the compiler reports

warning C4505: 'unusedFunction2' : unreferenced local function has been removed

for the static function unusedFunction2(). But it doesn't report anything for unusedFunction1().

It seems that including local function in the anonymous namespace suppresses the unreferenced local function warning, which is an unexpected and unpleasant side-effect for me.

Is there any method to generate warnings for unreferenced local function in anonymous namespace, either with MSVC or other C++ compilers?

1

There are 1 answers

0
MuertoExcobito On BEST ANSWER

Depending on which C++ standard you're reading, it may contain this note in section 7.3.1 on unnamed namespaces:

"Although entities in an unnamed namespace might have external linkage, they are effectively qualified by a name unique to their translation unit and therefore can never be seen from any other translation unit." (eg. http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2011/n3242.pdf).

This implies that it is possible for the compiler to produce anonymous namespace symbols with external linkage. Inspecting the .obj file, this is in fact what MSVC is doing with 'unusedFunction1':

dumpbin /symbols a.obj | findstr "unusedFunction"
1345 00003B20 SECT1B notype ()    External     | ?unusedFunction1@?A0xd43c5f4a@@YAXXZ (void __cdecl `anonymous namespace'::unusedFunction1(void))

Because the function has external linkage, the compiler can't know whether it is used by another compilation unit or not, and thus doesn't throw the warning. It appears other compilers make a better choice about using internal linkage.