如何使用C宏(#define)更改调用,但不更改原型 [英] How to use C macro's (#define) to alter calls but not prototypes

查看:61
本文介绍了如何使用C宏(#define)更改调用,但不更改原型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们应用程序中的旧代码包含对 malloc realloc free 的调用.使用我们更新的代码,将调用我们自己的实现,而不是标准的运行时实现.示例如下所示,

Older code in our application contains calls to malloc, realloc and free. With our updated code, our own implementations are called instead of the standard runtime ones. Examples are shown below,

#define malloc(s) OurMalloc(s)
#define free(p)   OurFree(p)

这对于更新的代码和新的C ++代码都很好,我们只需实现全局 new delete 运算符,因此C ++解决方案更干净".

This works fine for the updated code and for the newer C++ code we simply implement global new and delete operators, so the C++ solution is 'cleaner'.

问题在于,我们现在必须包括一个第三方库,该库包含的类所包含的方法具有诸如 malloc free 之类的名称,例如

The problem is that we now have to include a 3rd party library, which has classes that contain methods that have names like malloc and free, e.g.

   class ABC
   {
      public:
      ...
      void free (char *p);
   };

如果该类的free方法具有相同数量的参数,则C/C ++预处理器会简单地用 ourFree 替换所有出现的 free ,即使在类定义中也是如此,即使调用没有 ABC 类的方法时也是如此.所以上面和下面的类定义调用:

If the free method of the class has the same number of arguments, the C/C++ preprocessor simply replaces all occurrences of free by ourFree, even in the class definition, even when calling the method free of the class ABC. So the class definition above and the following call:

ABC abc;
abc.free(p);

替换为

class ABC
   {
   public:
      ...
      void OurFree (char *p);
   };

ABC abc;
abc.OurFree(p);

可能会编译,但是当然不会链接.

Which may compile, but which doesn't link of course.

如果 ABC :: free 的参数数量与标准free的参数数量不同,则编译器仍会发出警告.我们想避免它们.

If ABC::free has a different number of arguments than the standard free, the compiler still gives a warning. we would like to avoid them.

一些替代解决方案是:

  • 在第三方开始时未定义我们的定义包括文件,稍后再重新定义
  • 确保在我们自己定义的内容之前始终包含第3方包含文件

但是即使这样,如果需要我们的代码来调用第三方类的这些malloc或free方法,则预处理器仍会更改这些调用,除非我们这样编写所有调用:

But even then, if our code is required to call these malloc or free methods of the 3rd party classes, the preprocessor will still alter the calls, unless we write all calls like this:

(abc::free)(p)

有没有一种方法可以告诉C/C ++预处理器进行定义?

Is there a way to tell a C/C++ preprocessor define that?

  • 仅纯C呼叫必须被替换
  • 不得替换原型
  • 不得替换类中的方法

推荐答案

预处理器对范围和语义一无所知.答案很短-不,您不能这样做.

Preprocessor know nothing about about scope and semantic. So short answer - no, you can't do that.

但是,您可以在库模块中使用 #undef free .另一方面,如果您从代码中调用方法 abc.free(),这将无济于事.

But, you can use #undef free in library modules. On other side - this will not help, if you call methods abc.free() from your code.

这篇关于如何使用C宏(#define)更改调用,但不更改原型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆