2015-11-19 34 views
5
#include <stdio.h> 

int main(){ 
     __asm__ (
       "result: \n\t" 
       ".long 0 \n\t" 
       "rdtsc  \n\t" 
       "movl %eax, %ecx\n\t" 
       "rdtsc  \n\t" 
       "subl %ecx, %eax\n\t" 
       "movl %eax, result\n\t" 
     ); 

     extern int result; 
     printf("%d\n", result); 
} 

我想通过result变量从汇编器通过一些数据main。这可能吗?我的汇编程序代码导致Segmentation fault (core dumped)。我使用Ubuntu 15.10 x86_64,gcc 5.2.1。传递变量从汇编到C

+0

GCC有[扩展ASM(https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html)对于这一点,让你参考到'__asm__'片段中的输出变量。 –

+2

要补充说明的是:代码就像在程序的代码段中为'result'分配空间,'.long 0'产生两个'add%al,(%rax)'指令。 –

+0

如果你想读时钟,为什么不使用'unsigned long long a = __builtin_ia32_rdtsc()'?那么你不需要写任何asm。 –

回答

1

更好的方法可能是:

int main (void) 
{ 
    unsigned before, after; 

    __asm__ 
    (
     "rdtsc\n\t" 
     "movl %%eax, %0\n\t" 
     "rdtsc\n\t" 
     : "=rm" (before), "=a" (after) 
     : /* no inputs */ 
     : "edx" 
    ); 

    /* TODO: check for after < before in case you were unlucky 
    * to hit a wraparound */ 
    printf("%u\n", after - before); 
    return 0; 
}