Search code examples
c++gccassemblyg++inline-assembly

Error in simple g++ inline assembler


I'm trying to write a "hello world" program to test inline assembler in g++. (still leaning AT&T syntax)

The code is:

#include <stdlib.h>
#include <stdio.h>

# include <iostream> 

using namespace std;

int main() {
    int c,d;

    __asm__ __volatile__ (
        "mov %eax,1;    \n\t"
        "cpuid;         \n\t"
        "mov %edx, $d;  \n\t"
        "mov %ecx, $c;  \n\t"
    );

    cout << c << " " << d << "\n";

    return 0;
}

I'm getting the following error:

inline1.cpp: Assembler messages:
inline1.cpp:18: Error: unsupported instruction `mov'
inline1.cpp:19: Error: unsupported instruction `mov'

Can you help me to get it done?

Tks


Solution

  • Your assembly code is not valid. Please carefully read on Extended Asm. Here's another good overview. Here is a CPUID example code from here:

    static inline void cpuid(int code, uint32_t* a, uint32_t* d)
    {
        asm volatile ( "cpuid" : "=a"(*a), "=d"(*d) : "0"(code) : "ebx", "ecx" );
    }
    

    Note the format:

    • first : followed by output operands: : "=a"(*a), "=d"(*d); "=a" is eax and "=b is ebx
    • second : followed by input operands: : "0"(code); "0" means that code should occupy the same location as output operand 0 (eax in this case)
    • third : followed by clobbered registers list: : "ebx", "ecx"