Inline Assembly Code
Inline Assembly Code
by
Usama Raheem
19011519-002
Inline Assembly
• Assembly language source code that is inserted directly into a HLL program.
• Compilers such as Microsoft Visual C++ and Borland C++ have compiler-specific
directives that identify inline ASM code.
• Efficient inline code executes quickly because CALL and RET instructions are not
required.
• Simple to code because there are no external names, memory models, or naming
conventions involved.
• not portable because it is written for a single platform.
Inline Assembly (cont’d)
__asm statement
_asm directive in Microsoft Visual C++
• Assembly Language statements are embedded into the C code __asm {
• Separate assembly module is not necessary statement-1
• Can be placed at the beginning of a single statement statement-2
• Assembly statement are identified by placing the keyword asm ...
• We Can use () to compound several assembly statements statement-n
}
Inline Assembler Overview
• Inline assembly code can use any C or C++ variable or function name that is in
scope.
• The asm keyword Call on the inline assembler and can appear wherever a C or C+
+ statement is legal.
• Variables and other symbols are defined in C++ code can be assessed from assembly code
• Only the part of C++ code that cannot be coded in C++ is coded in assembly
• Grammar
asm-statement:
asm assembly-instruction ;opt
asm { assembly-instruction-list } ;opt
assembly-instruction-list:
assembly-instruction ;opt
assembly-instruction ; assembly-instruction-list ;opt
asm
• Alternatively, you can put asm in front of each assembly instruction:
asm mov al, 2
asm mov dx, 0xD007
asm out dx, al
• Because the asm keyword is a statement separator, you can also put assembly
instructions on the same line:
asm mov al, 2 asm mov dx, 0xD007 asm out dx, al
Asm
• All three examples generate the same code, but the first style (enclosing the asm
block in braces) has some advantages.
• The braces clearly separate assembly code from C or C++ code and avoid needless
repetition of the asm keyword.
• Braces can also prevent ambiguities. If you want to put a C or C++ statement on the
same line as an asm block, you must enclose the block in braces. Without the braces,
the compiler cannot tell where assembly code stops and C or C++ statements begin.
Using C or C++ in asm Blocks
• Typedef(reserved-keywords) names, generally used with operators such as PTR and TYPE
or to specify structure or union members
Commenting styles
All of the following comment styles are acceptable, but the latter two
are preferred:
Example:
• the example pushes pointers to world, hello, and format, in that order, and then calls
printf.
Register usage
• In general, we can modify EAX, EBX, ECX, and EDX in our inline code because the
compiler does not expect these general purpose register values to be maintain
between statements
• Always save and restore ESI, EDI, and EBP.