如何在Visual Studio中使用预编译库构建应用程序

时间:2012-03-15 17:56:00

标签: c++ c visual-studio-2010

我正在使用我在Visual Studio 2010中编写的预编译库(.lib)。我的解决方案有两个项目。第一个项目(C)构建库。第二个项目(C ++)是一个Win32控制台应用程序,用于测试库。我尝试过的所有内容都无法解决链接器错误。 (我认为这很容易,因为一切都在同一个解决方案中。)任何指针都会受到赞赏。感谢。

以下是我得到的链接器错误:

  

1> MyProject.obj:错误LNK2019:函数_wmain中引用的未解析的外部符号“void __cdecl my_function(void)”(?my_function @@ YAXXZ)

     

1> C:\ Documents and Settings \ user \ Desktop \ MySolution \ Debug \ MyProject.exe:致命错误LNK1120:1个未解析的外部

这是Win32控制台应用程序的代码:

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

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

  return 0;
}

以下是my_function中声明my_api.h的方式:

extern VOID my_function(VOID);

2 个答案:

答案 0 :(得分:2)

您需要declare your function with C linkage才能让链接器理解这些函数是用C代码定义的,而不是C ++代码:

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

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

#ifdef __cplusplus
}
#endif

如果你只有一个功能,你可以放下大括号:

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

答案 1 :(得分:1)

确保库项目的输出目录(无论$(OutDir)扩展到该项目中)是否位于测试项目的链接器搜索路径上。为此,请转到项目“属性”对话框。在Linker -> General下,确保在Additional Library Directories中设置了目录。此外,请确保在Linker -> Inputmy_api.lib列出了库本身(Additional Dependencies)。