In: Electrical Engineering
How to use or embed assembly routines/codes in C programs?
Many programmers are more comfortable writing in C, and for good reason: C is a mid-level language (in comparison to Assembly, which is a low-level language), and spares the programmers some of the details of the actual implementation.
However, there are some low-level tasks that either can be better implemented in assembly, or can only be implemented in assembly language. Also, it is frequently useful for the programmer to look at the assembly output of the C compiler, and hand-edit, or hand optimize the assembly code in ways that the compiler cannot. Assembly is also useful for time-critical or real-time processes, because unlike with high-level languages, there is no ambiguity about how the code will be compiled. The timing can be strictly controlled, which is useful for writing simple device drivers. This section will look at multiple techniques for mixing C and Assembly program development.
Inline AssemblyEdit
One of the most common methods for using assembly code fragments in a C programming project is to use a technique called inline assembly. Inline assembly is invoked in different compilers in different ways. Also, the assembly language syntax used in the inline assembly depends entirely on the assembly engine used by the C compiler. Microsoft C++, for instance, only accepts inline assembly commands in MASM syntax, while GNU GCC only accepts inline assembly in GAS syntax (also known as AT&T syntax).
#include<stdio.h> void main() { int a = 3, b = 3, c; asm { mov ax,a mov bx,b add ax,bx mov c,ax } printf("%d", c); }
2) #include "stdio.h" #include<iostream> int main(void) { unsigned char r1=0x90,r2=0x1A,r3=0x2C; unsigned short m1,m2,m3,m4; __asm__ { MOV AL,r1; MOV AH,r2; MOV m1,AX; MOV BL,r1; ADD BL,3; MOV BH,r3; MOV m2,BX; INC BX; DEC BX: MOV m3,BX; SUB BX,AX; MOV m4,AX; } printf("r1=0x%x,r2=0x%x,r3=0x%x\n",r1,r2,r3); printf("m1=0x%x,m2=0x%x,m3=0x%x,m4=0x%x\n",m1,m2,m3,m4); return 0; }
Linked Assembly
When an assembly source file is assembled by an assembler, and a C source file is compiled by a C compiler, those two object files can be linked together by a linker to form the final executable. The beauty of this approach is that the assembly files can be written using any syntax and assembler that the programmer is comfortable with. Also, if a change needs to be made in the assembly code, all of that code exists in a separate file, that the programmer can easily access. The only disadvanges of mixing assembly and C in this way are that a)both the assembler and the compiler need to be run, and b) those files need to be manually linked together by the programmer.