简体   繁体   中英

error LNK2001: unresolved external symbol

I have two VC++ projects inside a sln file in visual studio 2010. I want to use a_flag in the file of another project, is this possible what i am doing below ?

Project 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;
}

Project 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"  ;
   }
}          

I set project1 as a DLL, project2 as an EXE project.

In linking, I am getting this error :

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

I have read Microsoft page here about the DLL creation and linking but no idea how to resolve this external symbol error.

Thanks !

You need to set the project that creates your .dll to also generate the .lib file (an import library).

A quick description of the linkage should be something like this :

DLL Dependency Project -> dependecy.dll + dependency.lib

Main Project -> depends at runtime to depedency.dll , depends at link time to dependency.lib.

In other words, your .dll is just another binary that exposes some function signatures.

At runtime you can choose for either c linkage which involves querying the dll for the exposed functors/variables via name (the hard way, but useful when you don't have the .dll source code at hand) or use a more elegant way where you link the generated static library with your main.

When using the 1st approach, you will need to treat inside your code if you cannot find a certain .dll .

When using the 2nd approach, your binary will know that it depends on a certain .dll when you try to run it .

Here's an answer you will find very useful : How do I build an import library (.lib) AND a DLL in Visual C++?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM