error LNK2019: unresolved external symbol in a mul

2019-08-02 11:55发布

I have a visual studio solution with multiple projects. One of them, "MyProject" is a static library (.lib). The project, among many other classes has two classes "A" and "B".

A.h:

#pragma once

class A
{
public:
    void foo();
};

A.cpp:

#include A.h

void A::foo(){
        //do something
}

B.h:

#pragma once

class B
{
public:
    void bar();
};

B.cpp:

#include B.h
#include A.h

void B::bar(){
        A a;
        a.foo();
}

Without compilation errors I'm getting the linkage error:

OtherProject.lib(B.obj) : error LNK2019: unresolved external symbol "public: void __thiscall A::foo(void)" (?foo@A@@QAE_NXZ) referenced in function "public: void __thiscall B::bar(void)" (?bar@B@@QAEXXZ)

Everything seems to be fine. I do see the compilation process of A.cpp. Building or linking only the project "MyProject" is fine. But when trying to build the whole solution I'm getting the error.

Thanks!

4条回答
▲ chillily
2楼-- · 2019-08-02 12:12

Either the implementation of this method is commented out in A.cpp:

void A::foo(){
        //do something
}

Or A.cpp is not included in the build of the project. Right click on A.cpp in the Solution Explorer and select Properties to see whether it is Excluded from Build. When you build, do you see this:

1>Compiling...
1>A.cpp

I typed this code into my Visual Studio and it worked fine.

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-08-02 12:17

another solution to this you can merge .h and .cpp files. In this way you will get solution to this. In my case, I did like this and it works well

查看更多
倾城 Initia
4楼-- · 2019-08-02 12:24

It turns out that, there is another project OtherProject that includes class B and uses it's function bar(). I didn't read the error good enough and didn't notice that the linkage error occurs in another project. All I had to do is include A.cpp in OtherProject.

查看更多
看我几分像从前
5楼-- · 2019-08-02 12:28

In Visual-Studio most linkage problems are related to forget adding .cpp files.

Check out all the implementation files are added to the project. Then clean-and-build your project.

查看更多
登录 后发表回答