1

I was looking how memory barriers are used in the kernel (Linux kernel v4.19-rc5). I don't understand the difference between asmasm and __asm__. For example, consider barrier function:

static inline void barrier(void)
{
    asm volatile("" : : : "memory");
}

This function uses asm and volatile keywords and it is a software barrier. On the other hand, consider a hardware barrier like this one:

#define mb()    __asm__ __volatile__("mb": : :"memory")

This time, the keywords __asm__ and __volatile__ were used. What is the difference between them? I understand from this post that the difference comes from the compiler but I don't understand why both versions (__asm__ and asm) were used in the same source code?

mip
  • 161
  • 1
  • 7

1 Answers1

3

Did you read @Ciro's answer on that question? What is the difference between 'asm', '__asm' and '__asm__'?.

It explains that asm and __asm__ are the same except that gcc -std=c99 disables asm, leaving only __asm__.

asm is a convenience name for __asm__, and is available in GNU C mode, which is the default (-std=gnu99 / -std=gnu11 or whatever).


There is exactly zero difference in behaviour. Some contributors to Linux preferred __asm__, while others used asm. Linux is compiled with -std=gnu99 or gnu11, because it definitely depends on GNU extensions to C.

I don't think either of those occurrences were in header that could be included elsewhere, outside of Linux. __asm__ isn't wrong in GNU C code. But if you need code to work even when compiled with -std=c11, then asm is wrong.


Only MSVC's __asm keyword is different, and uses __asm { insn; insn; } and isn't supported by mainline gcc. (Apple's gcc for older OS X that uses an LLVM back-end supports -fasm-blocks, like current Clang.)

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
  • Actually it's oDisPo's answer to the question you linked that more correctly answers this question. The choice of `asm` versus `__asm__` isn't (or shouldn't be) by preference. – Ross Ridge Sep 28 '18 at 14:30
  • @RossRidge: That's kind of what I was trying to say, that `asm` is a convenience name for `__asm__`, and is available in GNU C mode. But even though Linux is definitely dependent on GNU C, some contributors still preferred `__asm__` I guess. Or maybe it was going into headers that could be included elsewhere? `__asm__` isn't *wrong* in GNU C code. – Peter Cordes Sep 28 '18 at 14:33
  • The `__asm__` keyword should be used in `.h` files because `.c` files may use macros to redefine `asm` to mean something else. The `asm` keyword should be used in `.c` files because it's shorter and its safe to use because `.h` files shouldn't redefine it to mean something else. – Ross Ridge Sep 28 '18 at 14:44