Inline Assembly in C++ code

Posted: October 5, 2012 in Live in a Cloudy World, Microprocessor, Virtualization

After one of my previous blog post about C++, I had to know the way how I can include my assembly code into my C++ file. I used to code with assembly for my graduation project in my college, mainly about Hypervisors. My first step was about to know the CPUID of the Microprocessor (I work on Intel Microprocessor). Then to see if the VMX is turned on or not.

I usually code C++ on Ubuntu and I had to code some basic things with the assembly, I faced a lot of problems that’s why I want to share it with you.

There are several ways to include them together:

  • The first one is to compile each file differentially and then link them together (I think this is the easiest way). Here is a link I found very nice explaining so.
  • The second way is to include the assembly code in your C++ code.
    • For coding on windows platform, will need you to define that this function or this instruction is done by the assembly code by just writing __asm { assembly code goes here } before the instruction. Like in this link
    • For coding on Linux platform, to include the assembly language in it, it will be a little different you have to write __asm__ volatile { assembly code goes here }

      PS: coding assembly on the Linux platform is a little strange, actually I am sure of the reason, I think it is related how the AT&T labs made it possible. For example for moving a values from registers to another you have to write down % before it. “movl %EAX, %EBX“.

So let’s get into a very simple code:

Mov eax, 10

Mov ebx 10

Add eax, ebx


And here is the C++ code and the assembly included in:

        __asm__ volatile{“movl $10, %eax;”

“movl $10, %EBX;”

“addl %ebx, %eax”}


One of the major problems I faced was this error: “operand number out of range”, that will be for the reason that each platform will require a different syntax to include your assembly in it. Please if you face any problem, please let me know so I can help you J


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s