使用宏覆盖静态函数名称

时间:2018-09-27 14:06:14

标签: c c-preprocessor

我想在不修改原始代码的情况下进行运行时测量(实际上不是我的代码),代码如下:

Code.c:

#define CODE_SOURCE
#include "GlobalInclude.h"
#include "Code.h"

unsigned int Add(unsigned int x, unsigned int y)
{
  while(x--)
  {
    y++;
  }
  return y;
}

Code.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)中声明和定义的方法在某种程度上可行吗?我没有找到任何可能的解决方案。

1 个答案:

答案 0 :(得分:0)

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

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

如果.c文件和所有包含的标头被视为只读,则否,这是不可能的。