c++ - 如何使用宏替换赋值操作以用于锁定函数

标签 c++ macros

在函数的开头,我调用这个宏来防止重新进入函数:

//For locking ISRs to prevent re-entrant execution when nested interrupts are enabled 
//-ex: to prevent re-entrant execution of this ISR even though ***nested interrupts are enabled!***
//-"return" is to exit the function if the ISR is locked 
#define functionLock()              \
  static bool ISR_locked = false;   \
  if (ISR_locked==true)             \
    return;                         \
  ISR_locked = true;                \

这行得通。

在函数结束时,我想使用这个宏来为下一个入口重新启用该函数:

#define functionUnlock() ISR_locked = false;

但是,编译失败。错误:

error: '#' is not followed by a macro parameter
error: 'functionLock' was not declared in this scope
error: 'ISR_locked' was not declared in this scope

我的第二个宏有什么问题?

如果我只是删除第二个宏并使用“ISR_locked = false;”直接在函数的末尾,一切正常,但我想要一个匹配的宏来结束函数,而不是使用那一行。

目标是在函数中使用这些宏,如下所示:

void myISR()
{
  functionLock(); //locks the function to prevent re-entrant execution
  //do stuff
  functionUnlock();
}

完整的最小示例

#include <iostream>
using namespace std;

//macros:
//For locking ISRs to prevent re-entrant execution when nested interrupts are enabled
//-ex: to prevent re-entrant execution of this ISR even though ***nested interrupts are enabled!***
//-"return" is to exit the function if the ISR is locked
#define functionLock()              \
  static bool ISR_locked = false;   \
  if (ISR_locked==true)             \
    return;                         \
  ISR_locked = true;                \
#define functionUnlock() ISR_locked = false;

void myISR()
{
  functionLock();
  cout << "hello";
  functionUnlock();
//  ISR_locked = false;
}

int main()
{
  myISR();
  return 0;
}

最佳答案

从 functionLock 定义的最后一行删除\。

关于c++ - 如何使用宏替换赋值操作以用于锁定函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36274719/

相关文章:

c++ - 不能在函数中声明运算符。 Clang错误或规范?

c++变量没有在宏中命名类型

error-handling - 在 defmacro 中指示错误的常规方法是什么?

c++ - OpenGL 1.x 显示带有纹理的 GL_QUADS,纯色不

c++ - 使用对象的 Google Mock 和 SetArgPointee

c# - 如何从我的项目中删除不必要的资源?

c - 用于抽象的预处理器宏 - 良好实践?

c - 迭代结构成员的宏

macros - 在 Rust 的过程宏中使用 $crate?

c++ - std::vector 应该尊重 alignof(value_type) 吗?