darkrock76
darkrock76

Reputation: 171

Static Lib using namespace leads to unresolved external

I am using VS2013 and I have a static lib project with the following header:

#pragma once

namespace StaticLibNamespace
{
    void foo( void );
}

Then the function is defined in the cpp as follows:

#include "stdafx.h"
#include "StaticLibHeader.h"

using namespace StaticLibNamespace;

void foo( void )
{
    ;
}

In my simple console app, I include the reference to StaticLibNameSpaceTest.lib and my main function is the following:

#include "stdafx.h"
#include "..\StaticLibNamespaceTest\StaticLibHeader.h"


int _tmain(int argc, _TCHAR* argv[])
{
    StaticLibNamespace::foo();

    return 0;
}

If I try and compile this I get the following error: NamespaceTest.obj : error LNK2019: unresolved external symbol "void __cdecl StaticLibNamespace::foo(void)" (?foo@StaticLibNamespace@@YAXXZ) referenced in function _wmain

However if I change my static lib cpp file to the following everything is fine:

#include "stdafx.h"
#include "StaticLibHeader.h"

void StaticLibNamespace::foo( void )
{
    ;
}

I'm obviously not understanding everything going on with "using namespace" can someone please enlighten me? Thanks!

Upvotes: 2

Views: 327

Answers (1)

Greg Hewgill
Greg Hewgill

Reputation: 993095

The using namespace directive changes the lookup rules for symbols when the compiler sees an unqualified name and needs to find what it refers to.

However, in your case, you are defining a new function called foo. As an unqualified name, this defines a new foo in the global namespace (assuming there wasn't already one there). When you qualify the name, you are defining StaticLibNamespace::foo as you intend.

A different solution might be:

namespace StaticLibNamespace {

void foo( void )
{
    ;
}

} // namespace StaticLibNamespace

Upvotes: 3

Related Questions