来自另一个DLL的静态数据成员的未解析外部

时间:2014-08-19 18:07:39

标签: c++ windows dll dllimport afx

考虑定义From.dll类的From库的以下来源:

部首:

// From.h
#include <afxwin.h>
#include <afxext.h>

class AFX_EXT_CLASS From
{
    public:
        static const char staticMember[666];
};

实现:

// From.cpp
#include "From.h"

const char From::staticMember[] = "Total Crap";

必须在以下staticMember类中使用此库静态成员To,该类还必须生成DLL(To.dll):

部首:

// To.h
#include <afxwin.h>
#include <afxext.h>

class AFX_EXT_CLASS To
{
    public:
        static const char* retExtStatic();
};

实现:

// To.cpp
#include "To.h"
#include "From.h"

const char* To::retExtStatic()
{
    return From::staticMember;
}

但是,在链接LNK2001: unresolved external symbol "public: static char const * const From::staticMember" (?staticMember@From@@2QBDB)时,无论是直接在Visual Studio上还是在cmake生成的nmake中,我都会继续获得此To.dll

Linking CXX shared library To.dll
   Creating library To.lib and object To.exp
To.cpp.obj : error LNK2001: unresolved external symbol "public: static char const * const From::staticMember" (?staticMember@From@@2QBDB)
To.dll : fatal error LNK1120: 1 unresolved externals

第一个DLL被编译并链接好了。以下是我的CMakeLists.txt的相关部分:

add_definitions (-D_AFXDLL -D_AFXEXT -DPSAPI_VERSION=1)
set (CMAKE_MFC_FLAG 2) # Use MFC in a shared DLL

# FROM
file (GLOB FROM ${CMAKE_CURRENT_SOURCE_DIR}/From.cpp)
add_library (From SHARED ${FROM})
target_link_libraries (From)

# TO
file (GLOB TO ${CMAKE_CURRENT_SOURCE_DIR}/To.cpp)
add_library (To SHARED ${TO})
target_link_libraries (To From)

导出此静态数据成员的错误是什么?

1 个答案:

答案 0 :(得分:0)

正如@Niall和@Igor Tnadetnik在对这个问题的评论中指出的那样,当一个DLL需要另一个DLL时,如果在{{1}中声明了类,那么包含要使用的DLL的头文件是不安全的。 }。在这种情况下,由于客户端代码也是DLL,AFX_EXT_CLASS将被定义为AFX_EXT_CLASS而不是__declspec(dllexport)