rohit sharma
rohit sharma

Reputation: 115

Unresolved external symbol when using function in another file

I have one header file defined as:

A.h
class A
{
  void f1();
  void f2();
};

A.cpp
  void A::f1(){}
  void A::f2(){}

Now I am defining other application class where I want to use this class functions, so I created,

B.cpp
#include A.h

int main()
{
  A a1;
  a1.f1(); //linker error
}

But When I am calling this function it gives linked error like unresolved external symbol.

Upvotes: 1

Views: 1494

Answers (2)

David Hammen
David Hammen

Reputation: 33116

Linker errors and compiler errors are very different things. All that those function declarations in a #included file do is tell the compiler how to call those functions. The functions are defined elsewhere. The compiler doesn't need to know the definitions to know how to call them. Putting all those disparate pieces together is the job of the linker. If you don't supply the needed pieces to the linker you won't get an executable. You'll get a linker error instead.

You need to compile both A.cpp and B.cpp and then supply these to your linker. Just because the compiler and linker are oftentimes called by the same tool does not mean they are the same thing. They aren't. They have quite different jobs.

Upvotes: 3

Code-Apprentice
Code-Apprentice

Reputation: 83527

First of all, you should copy and paste the exact error rather than saying it's some error "like" such and such. You possibly can remove important details we need to answer your question.

In this particular case, the solution is rather straightforward. You need to create a project in Visual C++ and add all of your .cpp files to the project. When you compile, the linker should be able to find everything that it needs.

Upvotes: 4

Related Questions