【问题标题】:Passing variable from assembler to C将变量从汇编程序传递给 C
【发布时间】:2015-11-19 15:15:13
【问题描述】:
#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。

【问题讨论】:

  • GCC 对此有 Extended ASM,允许您引用该 __asm__ 片段中的输出变量。
  • 补充一点:代码在程序代码段中为result分配空间,.long 0产生两条add %al,(%rax)指令。
  • 如果你想读时钟,为什么不直接使用unsigned long long a = __builtin_ia32_rdtsc()呢?那你就不需要写任何asm了。

标签: c gcc assembly x86 inline-assembly


【解决方案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;
}

【讨论】:

    猜你喜欢
    • 2011-12-03
    • 1970-01-01
    • 2018-07-31
    • 1970-01-01
    • 2020-02-14
    • 2014-06-16
    • 1970-01-01
    • 2021-08-12
    • 2011-09-15
    相关资源
    最近更新 更多