错误LNK2001:未解析的外部符号

时间:2014-10-21 19:13:23

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

我在visual studio 2010的sln文件中有两个VC ++项目。我想在另一个项目的文件中使用 a_flag ,这可能是我在下面做的吗?

项目1:

**sample_header.h**


#ifndef SAMPLE_HEADER_API
#define SAMPLE_HEADER_API __declspec(dllimport) 
#endif
 extern SAMPLE_HEADER_API int a_flg;

**file1.cpp**
#define SAMPLE_HEADER_API __declspec(dllexport)
#include "sample_header.h"

// Intialization of external
int a_flag = 15;

void m_func()
{
  int i = 0;
}

项目2:

**file2.h**
 #include <stdio.h>

**file2.cpp**
 #include "file1.h"
 #include "sample_header.h"

 //  provided path of "sample_header.h" in additional include directory as well

void main()
{
   if(a_flag > 0)
   {
     std::cout << "FLAG"  ;
   }
}          

我将project1设置为DLL,将project2设置为EXE项目。

在链接中,我收到此错误:

error LNK2001: `unresolved external symbol "__declspec(dllimport) int a_flg" (__imp_?a_flg@@3HA)` in file2.cpp

我已阅读有关DLL创建和链接的Microsoft页面here,但不知道如何解决此外部符号错误。

谢谢!

1 个答案:

答案 0 :(得分:1)

您需要设置创建.dll的项目以生成.lib文件(导入库)。

链接的快速描述应该是这样的:

DLL依赖项目 - &gt; dependecy.dll + dependency.lib

主要项目 - &gt;在运行时取决于depedency.dll,取决于链接时间到dependency.lib。

换句话说,你的.dll只是另一个公开某些功能签名的二进制文件。

在运行时,你可以选择c链接,它涉及通过名称查询暴露的函子/变量的dll(困难的方法,但是当你手头没有.dll源代码时很有用)或者使用一种更优雅的方式,您可以将生成的静态库与主链接链接。

使用第一种方法时,如果找不到某个.dll,则需要在代码内部处理。

使用第二种方法时,您的二进制文件会在您尝试运行时知道它依赖于某个.dll。

这里有一个非常有用的答案: How do I build an import library (.lib) AND a DLL in Visual C++?

相关问题