Embedded Developer: June, 2014

Page 36

Mixing Assembly and C One of the most effective ways to make your code shorter, faster, and more efficient is to write it in assembly language. Using assembler may also enable you to take advantage of special instructions that are supported by the CPU but are not used by the C compiler. However, coding in assembler can be daunting for all but the smallest applications, and the code is not easily portable. This is why most code is written in C, and assembly language instructions are used only for a few critical functions. We need to have a proper balance between the code written in C and assembler. Here are the syntaxes used to mix assembly code within C in GCC and MDK compilers.

GCC Compiler Syntax asm(“..assembly code..”) is the syntax used to include assembly code inside a C file while using the GCC compiler. This syntax is to include a single line of assembly code within a “.c” file. The syntax for multi-line assembly code would be

asm(“ADD r0, r0, #1\n” “MOV r1, r0”); A local variable can be declared using assembly instructions using the following syntax: register int *foo asm(“r0”); Here foo is the integer type variable and it is forced to occupy register r0. Here is sample code accessing global variables (x and y) and performing a mathematical operations on them (Operation performed: y=x+1) asm(“LDR “LDR “LDR “ADD “STR

r0, r3, r1, r1, r1,

=x\n” =y\n” [r0]\n” r1, #1\n” [r3]”);

MDK Compiler _ _ asm(“..assembly code..”) is the syntax used to include assembly code inside a C file while using the MDK compiler. This syntax is to include a single line of assembly code within a “.c” file. The syntax for multi-line assembly code would be

asm (“line 1\n” “line 2\n” “line 3\n” ... “line n”);

_ _ asm (“line 1\n” “line 2\n” ... “line x\n”); or

Each line represents an assembly instruction.

_ _ asm { line 1 line 2 ... line x}

Here is an example where we increment the R0 register by 1 and move the value stored in r egister R0 to R1:

36


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.