2013-05-04 100 views
3

WINAPI非常新,所以要溫柔。WINAPI - 編譯時出錯LNK2019,LNK2001,LNK1120。

我已經閱讀了Jeffrey Richter的「通過C/C++編寫的Windows」一書,現在我正在嘗試做一些他在書中描述的基本DLL內容。

在第19章中,他舉了一個簡單的例子。我試圖讓這個例子,但建設項目時,我不斷收到這三個錯誤:

Error 1 error LNK2019: unresolved external symbol __imp__Add referenced in function [email protected]  
Error 2 error LNK2001: unresolved external symbol __imp__g_nResult 
Error 3 error LNK1120: 2 unresolved externals 

我有三個文件:

DLLChapter19.h:

#ifdef MYLIBAPI 
#else 
#define MYLIBAPI extern "C" __declspec(dllimport) 
#endif 
MYLIBAPI int g_nResult; 
MYLIBAPI int Add(int nLeft, int nRight); 

DLLChapter19.cpp:

//#include <Windows.h> //apparently the complier says that I should use stdafx.h instead(?) 
#include "stdafx.h" 
#define MYLIBAPI extern "C" __declspec(dllexport) 
#include "DLLChapter19.h" 

int g_nResult; 

int Add(int nLeft, int nRight) { 
    g_nResult = nLeft + nRight; 
    return(g_nResult); 
} 

然後(在另一個項目中,但在相同的解決方案中)。

DLLChapter19EXE.cpp:

//#include <Windows.h> //apparently the complier says that I should use stdafx.h instead? 
#include "stdafx.h" 
#include <strsafe.h> 
#include <stdlib.h> 

#include "C:\Users\Kristensen\Documents\Visual Studio 2012\Projects\DLLChapter19\DLLChapter19\DLLChapter19.h" 

int WINAPI _tWinMain(HINSTANCE , HINSTANCE , LPTSTR, int) { 

    int nLeft = 10, nRight = 25; 

    TCHAR sz[100]; 
    StringCchPrintf(sz, _countof(sz), TEXT("%d +%d =%d"), 
     nLeft, nRight, Add(nLeft, nRight)); 
    MessageBox(NULL, sz, TEXT("Calculation"), MB_OK); 

    StringCchPrintf(sz, _countof(sz), 
     TEXT("The result from the last Add is: %d"), g_nResult); 
    MessageBox(NULL, sz, TEXT("Last Result"), MB_OK); 
    return(0); 
} 

爲什麼會出現這三個錯誤?我看通過「DUMPBIN -exports」的DLLChapter19.dll,它看起來不錯,與2倍輸出的符號:

C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\bin\amd64>dumpbin -export 
s DLLChapter19.dll 
Microsoft (R) COFF/PE Dumper Version 11.00.60315.1 
Copyright (C) Microsoft Corporation. All rights reserved. 


Dump of file DLLChapter19.dll 

File Type: DLL 

    Section contains the following exports for DLLChapter19.dll 

    00000000 characteristics 
    5184F8EE time date stamp Sat May 04 14:02:54 2013 
     0.00 version 
      1 ordinal base 
      2 number of functions 
      2 number of names 

    ordinal hint RVA  name 

      1 0 000110C3 Add 
      2 1 00017128 g_nResult 

    Summary 

     1000 .data 
     1000 .idata 
     2000 .rdata 
     1000 .reloc 
     1000 .rsrc 
     4000 .text 
     10000 .textbss 

我已經搜查,搜查,但找不到我的問題的解決方案。

回答

2

編譯可執行文件時,這是一個鏈接器錯誤。該DLL很好,但你沒有告訴鏈接器如何鏈接到它。您需要將鏈接器傳遞到構建DLL時創建的導入庫(.lib文件)。

我認爲你使用的是Visual Studio。在這種情況下,將您的導入庫添加到附加庫依賴關係中爲您的可執行文件設置項目配置。

+0

非常感謝大衛,大衛! – 2013-05-04 13:20:44

0

「David Heffernan」給出的答案爲我工作。您需要將您的lib路徑添加到您的鏈接器路徑中,在{右鍵單擊您的項目} - >屬性 - >配置屬性 - >鏈接器 - >輸入 - >其他依賴項 - >編輯。

再次感謝「David Heffernan」。