views:

579

answers:

3

When building projects in C++, I've found debugging linking errors to be tricky, especially when picking up other people's code. What strategies do people use for debugging and fixing linking errors?

+1  A: 

One of the common linking errors I've run into is when a function is used differently from how it's defined. If you see such an error you should make sure that every function you use is properly declared in some .h file.
You should also make sure that all the relevant source files are compiled into the same lib file. An error I've run into is when I have two sets of files compiled into two separate libraries, and I cross-call between libraries.

Is there failure you have in mind?

Nathan Fellman
+1  A: 

The C-runtime libraries are often the biggest culprit. Making sure all your projects have the same settings wrt single vs multi-threading and static vs dll.

The MSDN documentation is good for pointing out which lib a particular Win32 API call requires if it comes up as missing.

Other than that it usually comes down to turning on the verbose flag and wading through the output looking for clues.

Rob Walker
+7  A: 

Not sure what your level of expertise is, but here are the basics.

Below is a linker error from VS 2005 - yes, it's a giant mess if you're not familiar with it.

ByteComparator.obj : error LNK2019: unresolved external symbol "int __cdecl does_not_exist(void)" (?does_not_exist@@YAHXZ) referenced in function "void __cdecl TextScan(struct FileTextStats &,char const *,char const *,bool,bool,__int64)" (?TextScan@@YAXAAUFileTextStats@@PBD1_N2_J@Z)

There are a couple of points to focus on:

  • "ByteComparator.obj" - Look for a ByteComparator.cpp file, this is the source of the linker problem
  • "int __cdecl does_not_exist(void)" - This is the symbol it couldn't find, in this case a function named does_not_exist()

At this point, in many cases the fastest way to resolution is to search the code base for this function and find where the implementation is. Once you know where the function is implemented you just have to make sure the two places get linked together.

If you're using VS2005, you would use the "Project Dependencies..." right-click menu. If you're using gcc, you would look in your makefiles for the executable generation step (gcc called with a bunch of .o files) and add the missing .o file.


In a second scenario, you may be missing an "external" dependency, which you don't have code for. The Win32 libraries are often times implemented in static libraries that you have to link to. In this case, go to MSDN or "Microsoft Google" and search for the API. At the bottom of the API description the library name is given. Add this to your project properties "Configuration Properties->Linker->Input->Additional Dependencies" list. For example, the function timeGetTime()'s page on MSDN tells you to use Winmm.lib at the bottom of the page.

Joe Schneider