2

I have the following code:

Header.hpp:

#ifndef HEADER_HPP_INCLUDED
#define HEADER_HPP_INCLUDED
#include<Windows.h>

extern HMODULE Module;
extern "C" bool __stdcall Initialized(void);
void (__stdcall *ptr_DetourPoint) (int X, int Y);

#endif //HEADER_HPP_INCLUDED

Header.cpp:

#include "Header.hpp"
HMODULE Module = nullptr;

bool __stdcall Initialize(void)
{
    Module = LoadLibrary("Point.dll");
    ptr_DetourPoint = reinterpret_cast<(__stdcall *)(int, int)>(GetProcAddress(Module, "PointFunc"));
    return ptr_DetourPoint != nullptr;
}

extern "C" __stdcall HookDetourPoint(int X, int Y)
{
    //Do stuff here..
    ptr_DetourPoint(X, Y);
}

main.cpp:

#include <windows.h>
#include "Header.hpp"

extern "C" bool __stdcall DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
    switch (fdwReason)
    {
        case DLL_PROCESS_ATTACH:
            Initialized();
            DisableThreadLibraryCalls(hinstDLL);
            break;

        case DLL_PROCESS_DETACH:
            break;

        default:
            break;
    }
    return true;
}

In the above, when I compile it using Mingw 4.8, I get:

obj\Release\main.o:main.cpp:(.bss+0xb78): multiple definition of `ptr_DetourPoint'
obj\Release\Implementations\Header.o:Header.cpp:(.bss+0xb80): first defined here

Any ideas why I get that? I don't want to have to typedef my function pointer.

Brandon
  • 22,723
  • 11
  • 93
  • 186

2 Answers2

3

The short answer is that ptr_DetourPoint declares a global function pointer, another piece of data like Module. To fix it, you could mark it as "extern" as well. But I doubt you need to expose it in your header, as it appears to just be an implementation detail in header.cpp.

Scott Jones
  • 2,880
  • 13
  • 19
3

The variable is defined in the header, which means that any source file that includes it defines that symbol. The result is that linking main.cpp and Header.cpp together defines ptr_DetourPoint twice. You need to define it in only one source file, and declare it as extern in a header if other files need to see it.

Jarryd
  • 1,312
  • 11
  • 17
  • But if I put extern then it says "undefined reference in Header.cpp :S Does that mean I need to copy the same code again into the .cpp file? – Brandon Jun 04 '13 at 03:08
  • Yes you need the same line without the extern in the cpp file. – Jarryd Jun 04 '13 at 03:09