C++ String passed to class constructor - linker errors


Keywords:c++ 


Question: 

I'm a C# programmer working on a C++ project in VS 2008, trying to create an instance of an object and pass it a string as a parameter for the constructor. When I do this, I'm getting linker errors which I'm really struggling to diagnose.

The linker errors I'm getting are

2>TestMyProj.obj : error LNK2028: unresolved token (0A0002B9) "public: __thiscall myNamespace::myClass::myClass(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >)" (??0myClass@myNamespace@@$$FQAE@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z) referenced in function "int __cdecl main(void)" (?main@@$$HYAHXZ)
2>TestMyProj.obj : error LNK2019: unresolved external symbol "public: __thiscall myNamespace::myClass::myClass(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >)" (??0myClass@myNamespace@@$$FQAE@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z) referenced in function "int __cdecl main(void)" (?main@@$$HYAHXZ)
2>..\MyProj\TestMyProj.dll : fatal error LNK1120: 2 unresolved externals

from the project (TestMyProj) which tries to create an instance of the class. MyProj compiles fine. The code is as below:

MyProj.cpp

#include "MyProj.h"

namespace myNamespace
{
    myClass::myClass(string inString){}
};

MyProj.h:

#pragma once
#include <string>
using namespace std;

namespace myNamespace
{
    class myClass
    {
    public:
        myClass::myClass(string inString);

    };

}

The code where I'm trying to create an instance of the class MyClass is in another project within the same solution

TestMyProj.cpp:

#include <string>
#include "../MyProj/MyProj.h"


int main()
{
    myNamespace::myClass("");
    return 0;
}

I'm obviously misunderstanding something fundamental, probably about the nature of header files. I'm largely working to previously coded examples.

Can anybody point out what I'm doing wrong?


2 Answers: 

You need to link the projects together. In C#, when you reference a class it automatically links the assembly. With C++ you have to reference the class by including the .h file, and link the projects.

Solutions are just ways of collecting projects together and mean nothing to the compiler.

I'm a fan of statically linked libraries to be honest, but if you really want to create a dll, see and the section called "To use the functionality from the class library in the app".



mostly myproj.lib is not added to the library files list. in linker configuration.