函数指针多重定义

Function Pointer multiple definition

本文关键字:定义 指针 函数      更新时间:2023-10-16

我有以下代码:

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;
}
在上面,当我使用Mingw 4.8编译它时,我得到:
objReleasemain.o:main.cpp:(.bss+0xb78): multiple definition of `ptr_DetourPoint'
objReleaseImplementationsHeader.o:Header.cpp:(.bss+0xb80): first defined here

知道为什么我得到这个吗?我不想为函数指针定义类型

简短的回答是ptr_DetourPoint声明了一个全局函数指针,另一个类似Module的数据块。要修复它,您也可以将其标记为"extern"。但我怀疑你需要在你的标题中暴露它,因为它似乎只是header.cpp中的实现细节。

该变量在头文件中定义,这意味着任何包含它的源文件都定义了该符号。结果是将main.cpp和Header.cpp链接在一起定义了两次ptr_DetourPoint。您只需要在一个源文件中定义它,如果其他文件需要看到它,则在头文件中将其声明为extern。