我创建了这个示例,其中包含3个Visual Studio项目:一个名为'Constants'
的DLL库,其中包含运行时常量(IDs
),另一个名为'Functions'
的DLL库使用了第一个常量库和一个控制台EXE,该控制台EXE通过调用'Functions'
库中的函数来打印出常量。
#pragma once
__declspec(dllexport) extern const int ID1;
__declspec(dllexport) extern const int ID2;
namespace {
int nextID();
}
#include "Constants.h"
const int ID1 = nextID();
const int ID2 = nextID();
namespace {
int nextID() {
static int ID = 0;
return ID++;
}
}
#pragma once
__declspec(dllexport) int getID1();
__declspec(dllexport) int getID2();
#include "Functions.h"
#include "Constants.h"
int getID1() {
return ID1;
}
int getID2() {
return ID2;
}
#include <iostream>
#include <Functions.h>
int main() {
std::cout << "Library Constants: " << std::endl;
std::cout << getID1() << std::endl;
std::cout << getID2() << std::endl;
std::cin.get();
return 0;
}
如果我将'Constants'
库直接链接到EXE并直接打印常量,那么一切正常,但是如果我将'Constants'
链接到'Functions'
然后将'Functions'
链接到EXE(使用getID
函数打印),然后出现此错误:
1>------ Rebuild All started: Project: Constants, Configuration: Debug Win32 ------
1>Constants.cpp
1> Creating library C:\dev\DLLTest\bin\Win32\Debug\constants.lib and object C:\dev\DLLTest\bin\Win32\Debug\constants.exp
1>Constants.vcxproj -> C:\dev\DLLTest\bin\Win32\Debug\constants.dll
2>------ Rebuild All started: Project: Functions, Configuration: Debug Win32 ------
2>Functions.cpp
2> Creating library C:\dev\DLLTest\bin\Win32\Debug\functions.lib and object C:\dev\DLLTest\bin\Win32\Debug\functions.exp
2>Functions.obj : error LNK2001: unresolved external symbol "int const ID1" (?ID1@@3HB)
2>Functions.obj : error LNK2001: unresolved external symbol "int const ID2" (?ID2@@3HB)
2>C:\dev\DLLTest\bin\Win32\Debug\functions.dll : fatal error LNK1120: 2 unresolved externals
2>Done building project "Functions.vcxproj" -- FAILED.
3>------ Rebuild All started: Project: Console, Configuration: Debug Win32 ------
3>Main.cpp
3>Console.vcxproj -> C:\dev\DLLTest\bin\Win32\Debug\console.exe
========== Rebuild All: 2 succeeded, 1 failed, 0 skipped ==========
我不明白为什么在这种情况下从DLL链接到DLL失败。
答案 0 :(得分:0)
Constants.h
应该是:
#pragma once
#ifdef CONSTANTS_DLLEXPORT
#define CONSTANTS_API __declspec(dllexport)
#else
#define CONSTANTS_API __declspec(dllimport)
#endif
CONSTANTS_API extern const int ID1;
CONSTANTS_API extern const int ID2;
namespace {
int nextID();
}
Functions.h
应该是:
#pragma once
#ifdef FUNCTIONS_DLLEXPORT
#define FUNCTIONS_API __declspec(dllexport)
#else
#define FUNCTIONS_API __declspec(dllimport)
#endif
FUNCTIONS_API int getID1();
FUNCTIONS_API int getID2();
然后需要将FUNCTIONS_DLLEXPORT
添加到'Functions'
项目的'预处理程序定义',并将CONSTANTS_DLLEXPORT
添加到'Constants'
项目的'预处理程序定义'。 / p>