当开发人员在 C 和 C++ 中添加调用函数 log_message 的代码时,我需要跟踪某个日志级别的每条日志消息。
这是为了项目中的日志消息管理,避免太多开发者在源代码中添加太多不遵循相同约定的消息。
例如:
文件1.c:
log_message("Module:Failed to create the file %s\n", file_name);
文件2.c:
log_message("Failed to create the XXXX file %s\n", file_name);
MESSAGE_1000 在另一个文件 message.h 中定义,该文件是从我们的消息数据库生成的。 消息.h:
const char* MESSAGE_1000 = “Module: Failed to create the file %s.\n”
文件预编译后:
file1.c 变成:
#include "message.h"
...
log_message(MESSAGE_1000,file_name)
file2.c 变成:
#include "message.h"
...
log_message(MESSAGE_1000,file_name)
当他们需要向日志消息数据库中添加一些新消息时。
他们可以使用一个可以被钩子(Hook)识别的固定函数名。
例如:
文件1.c:
log_message_new("My new message:%s", message)
编译期间:
message.h 更新为:
#defined MESSAGE_1001 "My new message:%s", message
在我们的消息数据库中,添加了一个新条目。
MESSAGE_1001="My new message:%s"
为什么会有消息数据库?它们适用于非开发人员。他们可以查看客户可能看到的所有日志消息。
这里我需要一个钩子(Hook)来捕获和修改源代码。
你有什么想法吗?
最佳答案
gcc 中有一个选项有时用于此类情况。您可以在链接时使用 -Wl,--wrap
模拟函数,参见 GNU ld linker options .
您将需要一个简单的编译单元:
extern "C" void __real_log_message(...);
extern "C" void __wrap_log_message(...) {
.... // do something with the arguments
__real_log_message(...); // call real function
}
将这些符号添加到您的链接过程并提供 -Wl,--wrap=log_message
链接选项,您就可以开始了。
关于c++ - 有没有在编译时替换函数的钩子(Hook)接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55001617/