Visual Studio and C++ – Getting started with inline assembler

Rather than rewriting what’s already out in the web, I want to share a pretty good ressource to get started with inline assembler in C++. To be more specific, I’ll cover C++ in Visual Studio 2013 with Microsoft Assembler (MASM).

From the blogs’ name, I guess the owner is called Rodrigo Savage and the entry I am mentionening and getting my information from is the following: http://rodrigosavage.blogspot.co.uk/2010/07/hello-world-with-inline-asm.html.

Let’s get out hands dirty and jump right into the code.

Walkthrough

I skip an explaination about the C++ syntax and will only focus on the relevant assembly parts.

Line 5-7 actually defines the parameters for the printf function from C++ we are calling. They must be outside of the scope of the main function. They will not be found by the compiler when they are placed inside of the main function. I think they always must be in the topmost scope or in global scope respectivly.

Line 11 indicates the start of an inline assembly block for C++. It must be followed by a pair of curly brakets, which contains the assembly code.

Line 13 – 24 contains the actual assembly code of MASM assembly. For the logic behind the pushing on the eax register, I refer to Rodrigo’s blog. It is depicted in detail over there.
First, the “world!”, then the “Hello” and last the format “%s %s\n” is put on the stack via register eax. The idea is to fetch the parameters from the stack and call printf function as follows:  printf("%s %s\n","Hello","world!") . The popping into ebx is used to clean up the stack.

Common mistakes

  • The three char arrays must be outside of the function scope. Otherwise they will not be found by the inline assembly code.
  • The assembly block does not start with __asm__. It is only __asm. In Visual Studio, the correct spelling will be indicated with a blue highlighting.
  • You must use curly brakets and not paranthesis for the assembly code block.
  • Popping the stack more or less often than you have pushed or pulled something on it, might end in an error.

 

 

Tags

Categories

Meta

Peter Merkert Written by:

Be First to Comment

Leave a Reply