使用rcmp库编译C++钩子项目遇语法错误求助
编译C++钩子项目时的rcmp库错误解决
错误信息
/root/lib-173/hook.cpp:14:77: error: expected constructor, destructor, or type conversion before ‘(’ token rcmp::hook_function<0x0809472A, int(gplayer_imp*, int, const void*, size_t)>([](auto original, gplayer_imp* self, int cmd_type, const void* buf, size_t size) { ^ /root/lib-173/hook.cpp:23:2: error: expected unqualified-id before ‘)’ token });
环境与代码
使用rcmp库进行函数钩子开发,相关代码如下:
hook.cpp
#define CATCH_CONFIG_MAIN #include "catch2/catch.hpp" #include <rcmp.hpp> #include <array> struct gplayer_imp; rcmp::hook_function<0x0809472A, int(gplayer_imp*, int, const void*, size_t)>([](auto original, gplayer_imp* self, int cmd_type, const void* buf, size_t size) { if (cmd_type == 174 && size < 6) { return 0; } return original(self, cmd_type, buf, size); });
CMakeLists.txt
cmake_minimum_required(VERSION 3.16) project(hook) set(CMAKE_SYSTEM_NAME Linux) set(CMAKE_SYSTEM_PROCESSOR x86_64) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(SOURCE_FILES hook.cpp) add_library(hook SHARED ${SOURCE_FILES}) target_compile_options(hook PRIVATE -std=c++17) add_subdirectory(/root/lib-173/rcmp) include_directories(/root/lib-173/rcmp/include) target_link_libraries(hook PRIVATE rcmp)
问题分析与解决
核心问题
错误根源是全局作用域中直接匿名初始化rcmp::hook_function的语法不符合C++规范,同时lambda的签名需要匹配rcmp的要求。
修复步骤
给
hook_function实例命名:全局作用域不能直接创建临时对象并传递lambda,必须声明一个变量来持有这个hook实例:// 将原来的匿名声明改为带变量名的定义 static auto my_hook = rcmp::hook_function<0x0809472A, int(gplayer_imp*, int, const void*, size_t)>( [](auto original, gplayer_imp* self, int cmd_type, const void* buf, size_t size) { if (cmd_type == 174 && size < 6) { return 0; } return original(self, cmd_type, buf, size); } );添加
static避免全局变量的链接问题,也可根据需求调整。显式指定原函数类型(可选):如果
auto original推导存在问题,可以显式指定原函数类型消除歧义:using TargetFunc = int(gplayer_imp*, int, const void*, size_t); static auto my_hook = rcmp::hook_function<0x0809472A, TargetFunc>( [](rcmp::original_t<TargetFunc> original, gplayer_imp* self, int cmd_type, const void* buf, size_t size) { // ... 原有逻辑 } );优化CMake配置:
- 移除
target_compile_options中的-std=c++17,因为CMAKE_CXX_STANDARD已经完成标准设置,避免重复配置 - 确保rcmp子项目也使用C++17,在
add_subdirectory前添加:set(CMAKE_CXX_STANDARD 17 PARENT_SCOPE)
- 移除
最终修正后的hook.cpp核心片段
struct gplayer_imp; using TargetFunc = int(gplayer_imp*, int, const void*, size_t); static auto my_hook = rcmp::hook_function<0x0809472A, TargetFunc>( [](rcmp::original_t<TargetFunc> original, gplayer_imp* self, int cmd_type, const void* buf, size_t size) { if (cmd_type == 174 && size < 6) { return 0; } return original(self, cmd_type, buf, size); } );
内容的提问来源于stack exchange,提问作者Adriano Kramer
相关产品推荐
相关产品推荐

