6
#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);
}

I would like to pass some data from assembler to main via the result variable. Is this possible? My assembler code causes a Segmentation fault (core dumped). I am using Ubuntu 15.10 x86_64, gcc 5.2.1.

3
  • GCC has Extended ASM for this, allowing you to refer to an output variable in that __asm__ fragment. Commented Nov 19, 2015 at 15:32
  • 2
    To add to that: the code as it stands allocates space for result in the program's code segment, and .long 0 produces two add %al,(%rax) instructions. Commented Nov 19, 2015 at 15:49
  • If you want to read the clock, why not just use unsigned long long a = __builtin_ia32_rdtsc()? Then you don't need to write any asm. Commented Nov 19, 2015 at 22:27

1 Answer 1

1

A better approach could be:

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.