用宏包装函数调用 [英] Wrap function call with macro

查看:61
本文介绍了用宏包装函数调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以仅使用宏包装函数调用?

Is it possible to wrap only function call with macro?

当我尝试

#define foo(x) bar(x)

它包装了函数调用和定义.

it wraps both function call and definition.

我知道使用链接器包装功能,但是在这种情况下,我无法使用此解决方案.

I know about wrapping function with linker, but in this case I can't use this solution.

让我们假设一些代码

#define foo(x) bar(z)

int foo(int z){
//some code
}

int bar(int x){
//some code
}

int function(){
int a = foo(2);
}

我想诠释a = foo(2);预处理后变为int a = bar(2).目前,我仅收到重新定义"错误.

I want to int a = foo(2); after preprocessing become int a = bar(2). Currently I only receive "redefinition" error.

我的示例显示了我想要实现的目标,但是在实际代码中,我必须将此宏通过cmake文件放入项目,而且我也无法修改目标文件中的源代码.抱歉,您之前没有提到它.

my example shows, what I want to achieve, but I in real code I have to put this macro to project via cmake file and I also can't modify source code in destination file. Sorry for not mention about it earlier.

推荐答案

使用undef来管理宏的生存期,而不用弄乱那些不知道宏的存在的代码段.

use undef to manage the lifetime of your macros and not to screw with sections of code that aren't aware of your macros' existence.

int foo(int z){
//some code
}

int bar(int x){
//some code
}

int function(){
    #define foo(x) bar(z)
    int a = foo(2);
    #undef foo
}

这个技巧扩展到诸如标头选项之类的东西,通常包括诸如Windows.h之类的东西,并且标头的定义取决于标头外部定义的定义,如下所示:

This trick extends to things like header options, often things like Windows.h are included and the header's defines depend on defines defined outside of the header as follows:

#define WIN32_LEAN_AND_MEAN // used in ifdef checks to not define/include rarely used stuff
#define NO_STRICT // used to allow HANDLE types to be used as void * without type errors
#define NO_MINMAX // used to avoid errors because MIN/MAX are already defined
#include <Windows.h>

此操作会使用标头完成解析后不再使用的宏来污染范围,因此您可以通过在include之后取消定义它们来清除它们:

this pollutes scope with macros that have no use after the header finished parsing, so you can clean up by undefing them after include:

#define WIN32_LEAN_AND_MEAN // used in ifdef checks to not define/include rarely used stuff
#define NO_STRICT // used to allow HANDLE types to be used as void * without type errors
#define NO_MINMAX // used to avoid errors because MIN/MAX are already defined
#include <Windows.h>
#undef NO_MINMAX 
#undef NO_STRICT 
#undef WIN32_LEAN_AND_MEAN

这使人们(尤其是C的初学者)更容易阅读您的代码,这知道这些是选项,并且在包含之后没有任何用处.这也使您可以进行有趣的类似于C ++的行为,例如基于包含之前定义的定义进行模板化,而不会多次包含标头而产生冲突.

This makes it easier for people reading your code, especially beginners to C to know that these are options and don't have any use after the include occurs. This also allows you to do interesting C++-like behaviors like templating based on defines defined before include, without conflicts of including headers multiple times.

这篇关于用宏包装函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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