忽略函数名为的define宏的参数

Ignoring the parameters for define macro with function name

本文关键字:define 参数 函数      更新时间:2023-10-16

今天,我听说C++程序员可以通过#define关键字做一些魔鬼般的事情。例如,

#define private public
#define class struct
#define sizeof(x) (sizeof(x) - 1)
#define true (__LINE__ % 2)
#define pthread_mutex_lock(m) 0 

我对function definition感兴趣。所以我试着通过进行测试

CRITICAL_SECTION g_critSec;
#define InitializeCriticalSection(n, y) 0

void comparemutexwithcriticalsection() {
    InitializeCriticalSection(&g_critSec);
    std::cout << "Iterations: " << g_cRepeatCount << "nr";
    // other codes...
}

它可以在VS2013下成功构建,以下是反汇编代码。

void comparemutexwithcriticalsection() {
00F9A710  push        ebp  
00F9A711  mov         ebp,esp  
00F9A713  sub         esp,0CCh  
00F9A719  push        ebx  
00F9A71A  push        esi  
00F9A71B  push        edi  
00F9A71C  lea         edi,[ebp-0CCh]  
00F9A722  mov         ecx,33h  
00F9A727  mov         eax,0CCCCCCCCh  
00F9A72C  rep stos    dword ptr es:[edi]  
    InitializeCriticalSection(&g_critSec);
    std::cout << "Iterations: " << g_cRepeatCount << "nr";
00F9A72E  push        0FB66F4h  
    InitializeCriticalSection(&g_critSec);

#define宏中的参数似乎被忽略了,对吗


基于以上,我尝试将define作为0 来实现我自己的功能

#define myfunc(a) 0
void myfunc(int a)
{
    cout << a << endl;
}

然而,它未能在VS2013下编译有人能帮我找出这里缺的东西吗?或者我有什么不对劲

首先让我们非常清楚,重新定义像private这样的语言关键字是未定义的,并且可能有多种行为方式。

然后,对于您的函数,问题是在定义函数之前创建#define。试试这个方法:

void myfunc(int a)
{
    cout << a << endl;
}
#define myfunc(a) 0

如果你按照你最初提议的方式做,你会在预处理后得到这个,而这显然是非法的:

void 0(int a)
{
    cout << a << endl;
}