12

Say I have this function called DoThis(const char *abc) in a file called one.cpp. So when I attempt to call this function from another function in a different source file (two.cpp), I get the error: error LNK2001: unresolved external symbol (C++), even though I used #include "one.h" What would I do to fix this?

J'e
  • 3,014
  • 4
  • 31
  • 55
user2549990
  • 203
  • 1
  • 4
  • 8

2 Answers2

19

That means that the definition of your function is not present in your program. You forgot to add that one.cpp to your program.

What "to add" means in this case depends on your build environment and its terminology. In MSVC (since you are apparently use MSVC) you'd have to add one.cpp to the project.

In more practical terms, applicable to all typical build methodologies, when you link you program, the object file created form one.cpp is missing.

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
  • But what if say my file is a header only file cause its an abstract class? Sorry to dig up old post :) – Niklas Vest Apr 01 '16 at 15:27
  • @Niklas Vest: If everything is there, in the header, then the compiler/linker should be able to find everything without any problems. I.e. LNK2001 simply will not occur. Placing inappropriate things into header files usually elevates risk of LNK2005, which is on the other end of the spectrum: too many definitions. – AnT stands with Russia Apr 01 '16 at 16:52
5

Sounds like you are using Microsoft Visual C++. If that is the case, then the most possibility is that you don't compile your two.cpp with one.cpp (one.cpp is the implementation for one.h).

If you are from command line (cmd.exe), then try this first: cl -o two.exe one.cpp two.cpp

If you are from IDE, right click on the project name from Solution Explore. Then choose Add, Existing Item.... Add one.cpp into your project.

Payton Wu
  • 69
  • 2