【发布时间】:2018-09-27 14:06:14
【问题描述】:
我想在不修改我的原始代码(实际上不是我的)的情况下进行运行时测量,代码如下所示:
代码.c:
#define CODE_SOURCE
#include "GlobalInclude.h"
#include "Code.h"
unsigned int Add(unsigned int x, unsigned int y)
{
while(x--)
{
y++;
}
return y;
}
代码.h:
#ifndef CODE_H
#define CODE_H
unsigned int Add(unsigned int x, unsigned int y);
#endif
Main.c:
#include "GlobalInclude.h"
#include "Code.h"
int main()
{
printf("5+6 = %d", Add(5,6));
return 0;
}
GlobalInclude.h
#ifndef GLOBALINCLUDE_H
#define GLOBALINCLUDE_H
#if defined CODE_SOURCE
#define Add(x,y) Add_Custom(x,y)
#endif
#endif
在此,我用自己的 Add_Custom 方法覆盖 Add 方法,并且可以进行一些运行时测量,例如:
#define STUB_SOURCE
#include "GlobalInclude.h"
#include "Code.h"
#define DO_SOMETHING()
unsigned int Add_Custom(unsigned int x, unsigned int y)
{
unsigned int result;
DO_SOMETHING();
result = Add(x,y);
DO_SOMETHING();
return result;
}
我现在的问题是,在 c 文件(Code.c)中声明和定义的方法是否有可能?我没有找到任何可能的解决方案。
【问题讨论】:
-
要打印
unsigned int类型的值,请在 printf 格式字符串中使用"%u",否则为 UB。 -
您可以使用 链接器 做一些“诡计”。我无能为力,只想给你另一个关键字来搜索。
-
@pmg:感谢您对链接器的想法。但实际上我希望有一个通用的解决方案,它不依赖于特定的工具(因为每个链接器都有自己的可能性,有些可能支持这些特性,有些则不。
标签: c c-preprocessor