有什么办法可以用宏重复一段C代码N次吗? N也是一个宏。
例如,如果我有这个宏:
#define N 5
#define COODE "nop\n\t"
#define REPEAT [...]
当我调用 repeat 时,预处理器写入 CODE N 次,所以
__asm__(REPEAT);
会变成
__asm__("nop\n\t""nop\n\t""nop\n\t""nop\n\t""nop\n\t");
我有一个 Arduino,它必须等待一个确切的(而且很小,大约 10-15)个时钟。每个“nop”(无操作)只需要 1 个时钟周期来执行,它什么也不做。我不能只做一个循环,因为每个循环都在不止一个操作中执行(初始化计数器,递增计数器,检查是否到达结束),所以我不想手动编写“nop\n\t”有一个宏。这样我也可以简单的改N来修改程序而不需要重写。
提前致谢
最佳答案
如果您想在不包含整个库或不使用 define 的情况下执行此操作,您可以使用简单递归模板:
//By Christopher Andrews, released under MIT licence.
template< unsigned N > struct Nops{
static void generate() __attribute__((always_inline)){
__asm__ volatile ("nop");
Nops< N - 1 >::generate();
}
};
template<> struct Nops<0>{ static inline void generate(){} };
void setup() {
Nops<10>::generate();
}
void loop(){}
这将生成所需的确切数量的 nop。
0000010a setup:
10a: 00 00 nop
10c: 00 00 nop
10e: 00 00 nop
110: 00 00 nop
112: 00 00 nop
114: 00 00 nop
116: 00 00 nop
118: 00 00 nop
11a: 00 00 nop
11c: 00 00 nop
11e: 08 95 ret
我已经在 Arduino 的 TFT 驱动程序中使用了这种方法。
编辑:
还有另一种方法可以在使用 avr-gcc 编译的 AVR 上轻松完成此操作。我假设这在旧的工具链上可能不可用。
In order to delay execution for a specific number of cycles, GCC implements
void __builtin_avr_delay_cycles (unsigned long ticks)
ticks is the number of ticks to delay execution. Note that this built-in does not take into account the effect of interrupts which might increase delay time. ticks must be a compile time integer constant; delays with a variable number of cycles are not supported
来自这里:https://gcc.gnu.org/onlinedocs/gcc-4.7.1/gcc/AVR-Built_002din-Functions.html
关于c++ - 用于重复代码的 C/C++ 宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26983548/