【发布时间】:2011-10-11 22:25:12
【问题描述】:
我在头文件(hook.h)中有一个 LRESULT CALLBACK 函数,我都转发声明然后在文件中定义(以及一些包含静态变量的类)。然后我在关联的 .cpp 文件 (hook.cpp) 中定义(实现/创建?)静态类变量。
最后我将头文件包含在我的 stdafx.h 文件中,以便我可以在我的程序中使用它。
因为我两次包含 hook.h 文件,我得到一个编译错误,即 LRESULT CALLBACK 函数被定义了两次,错误是:
stdafx.obj : error LNK2005: "long __stdcall LowLevelKeyboardProc(int,unsigned int,long)" (?LowLevelKeyboardProc@@YGJHIJ@Z) already defined in main.obj
1>main.obj : error LNK2001: unresolved external symbol "protected: static class LowLevelKeyboardHookEx * LowLevelKeyboardHookEx::instance" (?instance@LowLevelKeyboardHookEx@@1PAV1@A)
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
我也尝试过在 hook.cpp 中不包含 hook.h 文件而只包含 stdafx.h 但我遇到了同样的问题?
【问题讨论】: