【问题标题】:Problem with WndProc() in header file头文件中的 WndProc() 问题
【发布时间】: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 但我遇到了同样的问题?

【问题讨论】:

    标签: c++ winapi include


    【解决方案1】:

    将您的 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,但只链接了一个函数的定义。

    有一些替代解决方案,包括一些“内联”关键字和可能的 pragma/declspec 指令以使其工作。两者似乎都不适合您想做的事情。

    【讨论】:

      【解决方案2】:

      它不是 WndProc 问题,也不是预编译头问题。它更多的是在头文件中定义全局函数并将其包含在两个以上的源文件中。我想说的是,要么将函数定义放在源文件中,要么使用类静态函数。

      【讨论】:

        【解决方案3】:

        您应该将KeyboardProc 的实现放在您的hook.cpp 文件中。将原型留在标题中,但将代码移至.cpp

        【讨论】:

          猜你喜欢
          • 2012-01-18
          • 1970-01-01
          • 1970-01-01
          • 2011-08-12
          • 1970-01-01
          • 1970-01-01
          • 2013-01-24
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多