nasm vs汇编混编

Using Assembly from Microsoft Visual C++ 2010

Dr. Orion Lawlor, 2011-10-12

Step 1: Write C++ Code

First, hit File - New Project to make a standard C++ console application:

nasm vs汇编混编_第1张图片

Next, remove the Microsoft junk, like the procompiled header.

nasm vs汇编混编_第2张图片

Next, write some test C++ code. It helps to run at this point, to make sure everything works.

nasm vs汇编混编_第3张图片

Step 2: Write assembly code

Now write an assembly language source file with these critical pieces:

  • Give the file the .S extension, the standard extension for assembly code.
  • Start the file with "section .text", so the code is executable.
  • Make the function "global", so the linker can see it.
  • Make the function name begin with an underscore--for some reason Windows compilers stick an underscore on the front of every function name.
Finally, right click on your new file, and hit properties.

nasm vs汇编混编_第4张图片Visual doesn't know how to compile the .S file by default, so it ignores it: "Does not participate in build." Change this to "Custom Build Tool": nasm vs汇编混编_第5张图片 Now you need to download and install NASM(or YASM, etc.) You then give Visual Studio the Command Line needed to run your assembler, just like at the DOS prompt:

	"\Program Files\nasm\nasm" -f win32  asmstuff.S
The assembler will output a .obj file, which you list under "Outputs".

nasm vs汇编混编_第6张图片

Build the project, and you should be able to call assembly functions from your C++, and vice versa!  Don't forget extern "C" from C++!

nasm vs汇编混编_第7张图片

Simple C++ code:

#include 
extern "C" int foo(void); // written in assembly!

int main() {
	std::cout<<"Foo returns "< 
  Assembly code: 
  
section .text ; makes this executable
global _foo ; makes this visible to linker
_foo:
	mov eax,7 ; just return a constant
	ret

你可能感兴趣的:(汇编)