【问题标题】:Overwrite static function name using macros使用宏覆盖静态函数名
【发布时间】: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


【解决方案1】:

在内部链接/静态的情况下,您只能编写存在于同一翻译单元内的函数的“模拟”函数。因此,您要么必须修改 .c 文件,要么必须修改该文件包含的头文件之一。

破坏性最小的可能是创建一个包含在 C 文件中的“mock.h”,然后在此处添加一个类似于您问题中的宏。

如果.c文件和所有包含的头文件都被认为是只读的,那么不,这是不可能的。

【讨论】:

  • 可以操作 GlobalInclude.h 文件,但不能操作 Code.[c/h]。
猜你喜欢
  • 2020-07-17
  • 1970-01-01
  • 2012-09-21
  • 1970-01-01
  • 2011-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-20
相关资源
最近更新 更多