unable to link header and cpp file of one project's from another LNK2019: unresolved external symbol error

StackOverflow https://stackoverflow.com/questions/22369339

  •  13-06-2023
  •  | 
  •  

Question

I have a header file A.h

namespace DIV
{
    int Fun();
}

A source file A.cpp

namespace DIV
{
    class A
    {
    public:
        A(){}
        ~A(){}    
        int Fun();    
    };


    int A::Fun()
    {
        return 0;
    }        
}

Now I have another source file B.cpp in another project of the same solution.

This source uses google's GTest framework. Inside the test function I use

#include "gtest/gtest.h"
#include "A.h"
TEST(FunTest, Param)
{
    int value = DIV::Fun();
}

Because of the DIV::Fun() call I get linker error. I don't understand the reason behind the linker error.

EDIT: B.cpp is in an .exe project and A.h/cpp is in a lib project.

Était-ce utile?

La solution

Problem is solved. I have got the answer from here. To summarize I needed to link my exe project with the lib project which contains the function fun(). Now the simplest way to make the .exe project link against .lib project probably is by adding a reference:

  • In the .exe project's settings, select the section named "Common Properties" at the top of the section list.
  • You should now see a list of references that the .exe project has. The list is probably empty.
  • Click the "Add new reference" button at the bottom of the dialog and add the .lib project as a reference
  • When you select the new reference in the list of references you will see a set of properties for that reference. Make sure that the property called "Link Library Dependencies" is set to true. This will cause the .lib project to be added automatically as an input to the linker when you build the .exe project.

After that the linker error was gone.

Autres conseils

With extern and without extern keyword it works. You need to export your function fun to other modules/projects. Use __declspec(dllexport) .

What is the purpose of your use of extern here? Because functions have external linkage by default, marking functions extern for this reason is not necessary. However, this should not cause a linker error in this case.

The linker error indicates that the function definition is found but the object file is not properly linked. How are you compiling and linking the program?

EDIT:

Since A.cpp is not in the same project as B.cpp, you will need to explicitly link to the object files in your A.cpp project. Since it sounds like you are using Visual Studio, you may find this useful

How do you share code between projects/solutions in Visual Studio?

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top