如何用C宏的(#定义)改变电话,但不能原型 [英] How to use C macro's (#define) to alter calls but not prototypes

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

问题描述

在我们的应用程序的版本code包含的malloc 的realloc 通话免费。我们最新的code,我们自己的实现被调用,而不是标准运行的。例子如下所示,

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)

这为更新的code,而较新的C ++ code,我们简单地实现全球删除运营商,所以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 免费<名称的方法类/ code>,例如:

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);
   };

如果类的免费方法有相同数量的参数,C / C ++ preprocessor只需通过免费所有出现> ourFree ,即使在类的定义,即使调用方法自由之类的 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 ::免费有不同的参数个数比标准的自由,编译器仍然会发出警告。我们想避开他们。

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.

一些替代的解决方案是:

Some alternative solutions are:


  • 取消定义我们定义了第三方的开头包含文件,后来重新定义

  • 确保该第三方包含文件总是包括我们自己定义的

但即便如此,如果需要我们的code调用第三方类这些的malloc或免费的方式,在preprocessor仍​​然会改变来电,除非我们这样写所有来电:

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 ++ preprocessor定义?

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


  • 只有纯净的C-电话必须更换

  • 原型绝不能代替

  • 在类中的方法一定不能代替

推荐答案

preprocessor一无所知有关范围和语义。因此,简短的回答 - 不,你不能这样做,

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

不过,您可以在库模块使用和#undef免费。在另一边 - 这不会帮助,如果你调用方法 abc.free()从code

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宏的(#定义)改变电话,但不能原型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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