C++ 20: Inline Assembly
source link: https://www.tuicool.com/articles/BNnYVbi
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
asm-declaration gives the ability to embed assembly language source code within a C++ program. This declaration is conditionally-supported and implementation defined, meaning that it may not be present and, even when provided by the implementation, it does not have a fixed meaning.
Contents
[ edit ] Syntax
asm (
string_literal
)
;
[ edit ] Explanation
The string_literal is typically a short program written in assembly language, which is executed whenever this declaration is executed. Different C++ compilers have wildly varying rules for asm-declarations, and different conventions for the interaction with the surrounding C++ code.
As otherblock declarations, this declaration can appear inside a block (a function body or another compound statement), and, as all other declarations, this declaration can also appear outside a block.
This section is incompleteReason: write a note on GCC extended assembly syntax, since it is now supported by Intel, IBM, Sun (as of v12), etc
[ edit ] Examples
Demonstrates two kinds of inline assembly syntax offered by the GCC compiler. This program will only work correctly on x86_64 platform under Linux.
Run this code
#include <iostream> extern "C" int func(); // the definition of func is written in assembly language // raw string literal could be very useful asm(R"( .globl func .type func, @function func: .cfi_startproc movl $7, %eax ret .cfi_endproc )"); int main() { int n = func(); // extended inline assembly asm ("leal (%0,%0,4),%0" : "=r" (n) : "0" (n)); std::cout << "7*5 = " << n << std::endl; // flush is intentional // standard inline assembly asm ("movq $60, %rax\n\t" // the exit syscall number on Linux "movq $2, %rdi\n\t" // this program returns 2 "syscall"); }
Output:
7*5 = 35
[ edit ] External links
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK