2011-07-24 26 views
0

我在一個頭文件(hook.h)中有一個LRESULT CALLBACK函數,我都在該文件中轉發聲明和定義(以及一些包含靜態變量的類)。然後,我在關聯的.cpp文件(hook.cpp)中定義(實現/創建?)靜態類變量。在頭文件中的WndProc()的問題

最後,我將頭文件包含在stdafx.h文件中,這樣我就可以在程序中使用它了。

因爲我包括hook.h文件兩次我得到了LRESULT回調函數被定義了兩次編譯錯誤,錯誤的是:

stdafx.obj : error LNK2005: "long __stdcall LowLevelKeyboardProc(int,unsigned int,long)" ([email protected]@[email protected]) already defined in main.obj 
1>main.obj : error LNK2001: unresolved external symbol "protected: static class LowLevelKeyboardHookEx * LowLevelKeyboardHookEx::instance" ([email protected]@@[email protected]) 
1>C:\Users\Soribo\Dropbox\C++ Programming\Visual C++ Programming\Key Cataloguer\Release\Key Cataloguer.exe : fatal error LNK1120: 1 unresolved externals 

我如何才能避免這個問題?

我的頭文件:

#ifndef KEYBOARDHOOK_H 
#define KEYBOARDHOOK_H 

#include "stdafx.h" 

LRESULT CALLBACK KeyboardProc(int code, WPARAM wParam, LPARAM lParam); 

class MyClass { 
    public: 
     static std::string instanceStr; 
     // further down this class it refers to the function KeyboardProc() thus need for forward declaration 
}; 

LRESULT CALLBACK KeyboardProc(int code, WPARAM wParam, LPARAM lParam) 
{ 
    // implements function 
} 

#endif 

我hook.cpp文件:

#include "stdafx.h" 
#include "hook.h" 

std::string MyClass::instanceStr = ""; 

我的stdafx.h文件:

#pragma once 

#include "targetver.h" 

#define WIN32_LEAN_AND_MEAN    // Exclude rarely-used stuff from Windows headers 
// Windows Header Files: 
#include <windows.h> 

// C RunTime Header Files 
#include <stdlib.h> 

// Application Specific Includes 
#include <string> 
#include "hook.h"  // I think this is the cause of the error because I include this file twice in compilation which means that the LRESULT function is redefined/reimplemented 

我也曾嘗試不包括鉤。 h文件在hook.cpp &只包括stdafx.h但我得到同樣的問題?

回答

0

把你的KeyboardProc(或者它是LowLevelKeyboardProc?)的定義移動到hook.cpp中。也就是說,將這個代碼從hook.h移到hook.cpp中

LRESULT CALLBACK KeyboardProc(int code, WPARAM wParam, LPARAM lParam) 
{ 
    // implements function 
} 

但是讓KeybaordProc的「聲明」在hook.h中。也就是說,離開這行裏面hook.h:

LRESULT CALLBACK KeyboardProc(int code, WPARAM wParam, LPARAM lParam); 

這樣一來,任何其他來源的文件可以參考KeyboardProc,但只有一個函數的定義是與

有一些可供選擇的解決方案,包括。一些「內聯」關鍵字和可能的編譯指示/ declspec指令,使其工作。對於你想要做的事,這兩者似乎都不正確。

0

它不是WndProc問題,也不是預編譯頭問題。它更多的是在頭文件中定義一個全局函數,並將其包含在兩個以上的源文件中。我想說的是將函數定義放在源文件中,或者使用類靜態函數。

0

您應該將KeyboardProc的執行放入您的hook.cpp文件中。將原型留在標題中,但將代碼移至.cpp