Aussie AI
Inline Assembly Language
-
Book Excerpt from "Generative AI in C++"
-
by David Spuler, Ph.D.
Inline Assembly Language
Most C++ compilers support features allowing you to specify assembly language sequences in the middle of a C++ program, which is called “inline assembly language.” You don't need to put assembler into a separate code file, because you can use assembly language directives inside C++ sequences.
The directive to use to introduce an assembly language statement into C++ is somewhat compiler-dependent, but the whole concept of assembly language is platform-dependent anyway!
The “asm
” expression is the official C++ standard version.
This is like a function call with a semicolon ending it.
The asm
statement contains the assembly language statements
inside a large string constant, ending with a newline escape (i.e. “\n
”), inside round brackets.
Multiple assembly commands can be merged by putting two string literals on
subsequent lines and using the adjacent string literal concatenation feature of C++.
asm ( " ; ... instructions\n" // C++ Comment " ; ... more instructions\n" );
The Microsoft style is different,
with a code block rather than an expression.
You don't need to put the assembly statements inside a string literal,
and you don't need the “\n
” newline escapes, either.
The basic syntax looks like this:
__asm { ; ... instructions // C++ comment }
This is the Gnu and Clang style with “__asm__
” as a C++ function-like expression
(similar to “asm
”):
__asm__ ( " ; ... instructions\n" // C++ Comment );
Mixing C++ and assembly language is not something recommended just for fun.
Not only do you need to know the assembly statements and all about the CPU registers,
but you'll need to know about function calling conventions (e.g. __cdecl
vs __stdcall
vs __thiscall
) and name mangling in C++.
Which actually sounds kind of fun.
• Next: • Up: Table of Contents |
The new AI programming book by Aussie AI co-founders:
Get your copy from Amazon: Generative AI in C++ |