在我的代码中,我经常使用 for 循环来执行单个操作 n 次。例如:
// Wait for settle
int delayLoop = 0;
int count = 0;
for(delayLoop = 0; delayLoop < count; delayLoop++) {
__NOP(); // operation to do
}
起初我想将其作为一个函数......但后来我意识到我不知道如何将操作作为函数参数传递。
在上面的示例中,__NOP()
本身就是一个扩展为的宏:
__ASM volatile ("nop")
那么我怎样才能想出一个可以像这样调用的宏:
DO_LOOP(10, __NOP)
如果我需要进行更多操作怎么办?例如
DO_LOOP(8, __NOP, myFunction(arg1))
这将扩展为:
for(int i = 0; i < 8; i++) {
__NOP;
myFunction(arg1);
}
最佳答案
#define DO_LOOP(x, ...) for (int i = 0; i < x; ++i) { __VA_ARGS__; }
void f1() { printf("test\n"); }
void f2() { printf("a\n"); }
int main()
{
DO_LOOP(10, f1(), f2());
return 0;
}
gcc -E test.c
:
void f1() { printf("test\n"); }
void f2() { printf("a\n"); }
int main()
{
for (int i = 0; i < 10; ++i) { f1(), f2(); };
return 0;
}
但这不适用于内联汇编。您可以执行以下操作:
#define DO2(x, a, b) for (int i = 0; i < x; ++i) { a; b;}
并使用:
DO2(10, __NOP(), f1());
关于创建宏来执行单个操作 n 次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53188708/