简体   繁体   中英

How to use asm code in C++ & Visual Studio 2008

I am doing some cross-platform work, porting code from Linux to Win32, but when it comes to some assembly code, I cannot get it to work. This code compiles normally in Linux gcc, but will not work in VS2008 --win32.

Some of my code is below. What do I need to do if I want to compile it using VS2008 --win32 platform:

static inline void spin_wait(int n)
{
    int    tmp = n;
    while(tmp > 0) { tmp--; asm("" ::: "memory", "cc"); }
}

__asm__ __volatile__(
    "xorq        %%rdx, %%rdx    \n"
    "xorq        %%rax, %%rax    \n"
    "incq        %%rdx        \n"
    "lock cmpxchgq    %%rdx, (%1)    \n"
    "decq        %%rax        \n"
: "=a" (not_set) : "r" (n) : "%rdx");

If your question is about the use of inline assembly, you can still use it in Visual Studio ( MSDN link ) although you may need to tweak it for the platform of course.

For example:

__asm {
   mov al, 2
   mov dx, 0xD007
   out dx, al
}

A thing like "spin_wait" isn't portable, and should be (re)written to what's appropriate for the target platform. It's been a while since I've dealt with the horrible GAS syntax, but xorq means the snippet is for x86-64, right? The Microsoft compilers don't support inline assembly for 64bit targets.

Will _AcquireSpinLock perhaps do the trick?

For larger blocks of assembly (the parts that generally make sense to write in assembly), I'd advise you to use an external assembly module with a cross-platform assembler with sane syntax and a good feature set (for instance yasm, fasm or nasm). Of course that's not viable for something as critical and must-be-inline as a spinlock, though :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM