I have a LRESULT CALLBACK function in a header file(hook.h) that I both forward declare then define in the file(along with some classes that contain static variables). I then define(implement/create?) the static class variables in the associated .cpp file (hook.cpp).
Finally I include the header file in my stdafx.h file so I can use it in my program.
Because I include the hook.h file twice I get a compilation error that the LRESULT CALLBACK function is defined twice, the error is:
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
How can I avoid this issue?
My header file:
#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
My hook.cpp file:
#include "stdafx.h"
#include "hook.h"
std::string MyClass::instanceStr = "";
My stdafx.h file:
#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
I have also tried not including the hook.h file in hook.cpp & just including stdafx.h but I get the same issue?
Move your definition of KeyboardProc (or is it LowLevelKeyboardProc?) into hook.cpp. That is, move this code from hook.h into hook.cpp
But leave your “declaration” of KeybaordProc in hook.h. That is, leave this line inside hook.h:
That way, any other source file can reference KeyboardProc, but only one definition of the function is linked in.
There are some alternative solutions including some “inline” keywords and possibly a pragma/declspec directive to make it work. Neither seems right for what you want to do.