【发布时间】:2018-04-19 15:04:52
【问题描述】:
这很好用:
#include <stdio.h>
int main(){
volatile int abort_counter = 0;
volatile int i = 0;
while (i < 100000000) {
__asm__ ("xbegin ABORT");
i++;
__asm__ ("xend");
__asm__ ("ABORT:");
++abort_counter;
}
printf("%d\n", i);
printf("nof abort-retries: %d\n",abort_counter-i);
return 0;
}
然而,我原来写的是
#include <stdio.h>
int main(){
volatile int abort_counter = 0;
volatile int i = 0;
while (i < 100000000) {
__asm__ ("xbegin ABORT");
i++;
__asm__ ("xend");
continue;
__asm__ ("ABORT:");
++abort_counter;
}
printf("%d\n", i);
printf("nof abort-retries: %d\n",abort_counter);
return 0;
}
但这导致
/tmp/cchmn6a6.o: In function `main':
rtm_simple.c:(.text+0x1a): undefined reference to `ABORT'
collect2: error: ld returned 1 exit status
为什么?
(使用gcc rtm_simple.c -o rtm_simple编译。)
【问题讨论】:
-
编译器很可能优化了
continue之后的所有内容,因为它无法到达(而且它也不分析汇编代码,所以它不知道你在做什么)。 -
这只是一个猜测,但我认为编译器会将 continue 之后的行视为死代码(永远不会被执行),因此它会在编译时将其删除。 C 编译器不知道“xbegin ABORT”是什么意思。
-
使用
__asm__ __volatile__修复了吗? -
你检查
gcc -S rtm_simple.c的输出了吗? -
你也许能骗到它:
continue; reachable: __asm__("ABORT:"); ++abort_counter; } ... if (abort_counter < 0) goto reachable;
标签: c gcc while-loop inline-assembly continue