Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unresolved external symbol when linking to static lib with namespace

I ran into a behavior today that I don't completely understand. I jump right into a minimal code example and will explain along the way.

I have 2 Projects: A static c++ library and a console application.

Static Lib Project:

Library.h

#pragma once

namespace foo
{
    int testFunc();

    class StaticLibClass
    {
    public:
        static int testMemberFunc();
    };

}

Library.cpp

#include "Library.h"

using namespace foo;

// just some functions that don't do much
int testFunc()
{
    return 10;
}

int StaticLibClass::testMemberFunc()
{
    return 11;
}

Console Application Project:

main.cpp

#include "library.h"

using namespace foo;

void main()
{
    // calling this function reslts in LNK2019: unresolved external symbol...
    testFunc();

    // this function works just fine
    StaticLibClass::testMemberFunc();
}

As you can see the static member function of a class works just fine. The single testFunc however results in a linker error. Why is this?

The solution to the problem is to not use "using" in the Library.cpp file but also wrap it in the namespace like so:

Changes that fix the problem:

Library.cpp

#include "Library.h"

namespace foo
{

    // just some functions that don't do much
    int testFunc()
    {
        return 10;
    }

    int StaticLibClass::testMemberFunc()
    {
        return 11;
    }
}
like image 796
derkie Avatar asked Jul 13 '14 20:07

derkie


1 Answers

You either need to wrap the body of the implementation functions/methods in a namespace statement that matches the original header, or you can use fully qualified names which is probably better C++ style:

#include "Library.h"

// just some functions that don't do much
int foo::testFunc()
{
    return 10;
}

int foo::StaticLibClass::testMemberFunc()
{
    return 11;
}

You don't need a using namespace foo; in this version. You are already in the namespace 'foo' when implementing the body's of those two methods, but it can be convenient depending on other types in that namespace.

like image 113
Chuck Walbourn Avatar answered Oct 25 '22 00:10

Chuck Walbourn