1
votes

I am working with a precompiled library (.lib) that I wrote in Visual Studio 2010. My solution has two projects. The first project (C) builds the library. The second project (C++) is a Win32 console application that is intended to test the library. Everything I've tried does not resolve the linker errors. (I thought this would be easy because everything is in the same solution.) Any pointers would be appreciated. Thanks.

Here is the linker error that I am getting:

1>MyProject.obj : error LNK2019: unresolved external symbol "void __cdecl my_function(void)" (?my_function@@YAXXZ) referenced in function _wmain

1>C:\Documents and Settings\user\Desktop\MySolution\Debug\MyProject.exe : fatal error LNK1120: 1 unresolved externals

This is the code for the Win32 console application:

#include "stdafx.h"
#include "my_api.h"

int _tmain(int argc, _TCHAR* argv[])
{
  my_function();

  return 0;
}

Here's how my_function is declared in my_api.h:

extern VOID my_function(VOID);
2
Is the output directory of the .c library in the library path of the C++ project? Unfortunately, just having them in the same solution isn't enough (as opposed to C#, where it's dead easy) - Moo-Juice
Don't make us guess at the linker errors. - Hans Passant
@HansPassant: I do apologize. Thank you for your courteous suggestion. I've added the linker error and the code that causes it. - Jim Fell

2 Answers

2
votes

You need to declare your function with C linkage in order for the linker to understand that those functions were defined in C code, not C++ code:

// my_api.h
#ifdef __cplusplus
extern "C" {
#endif

extern VOID my_function(VOID);
// more function declarations etc.

#ifdef __cplusplus
}
#endif

If you only have one function, you can drop the braces:

// my_api.h
#ifdef __cplusplus
extern "C"
#endif
extern VOID my_function(VOID);
1
votes

Ensure that the output directory of the library project (whatever $(OutDir) expands to in that project) is on the linker search path for the test project. To do this, go to the project Properties dialog. Under Linker -> General, make sure the directory is set in Additional Library Directories. Further, make sure under Linker -> Input that the library itself (my_api.lib) is listed in Additional Dependencies.