Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does including assembly inline with C code work?

I've seen code for Arduino and other hardware that have assembly inline with C, something along the lines of:

asm("movl %ecx %eax"); /* moves the contents of ecx to eax */
__asm__("movb %bh (%eax)"); /*moves the byte from bh to the memory pointed by eax */

How does this actually Work? I realize every compiler is different, but what are the common reasons this is done, and how could someone take advantage of this?

like image 595
MDMoore313 Avatar asked May 23 '14 14:05

MDMoore313


People also ask

How does inline assembly work?

In computer programming, an inline assembler is a feature of some compilers that allows low-level code written in assembly language to be embedded within a program, among code that otherwise has been compiled from a higher-level language such as C or Ada.

Can you mix C and assembly?

C and Assembly can be used together to provide extra flexibility. You can create static libraries in Assembly that you call from C, and vice-versa, you can call C functions from within Assembly. Check out the code samples below that demonstrate that process.

Can we write assembly code in C?

We can write assembly program code inside c language program. In such case, all the assembly code must be placed inside asm{} block.


1 Answers

The inline assembler code goes right into the complete assembled code untouched and in one piece. You do this when you really need absolutely full control over your instruction sequence, or maybe when you can't afford to let an optimizer have its way with your code. Maybe you need every clock tick. Maybe you need every single branch of your code to take the exact same number of clock ticks, and you pad with NOPs to make this happen.

In any case, lots of reasons why someone may want to do this, but you really need to know what you're doing. These chunks of code will be pretty opaque to your compiler, and its likely you won't get any warnings if you're doing something bad.

like image 165
Scott Seidman Avatar answered Sep 22 '22 19:09

Scott Seidman