1.说明:Visual Studio工程系统通过使用MASM的方式支持在C++项目中使用汇编语言文件。
MASM完全支持x64汇编语言源文件, 并自动将它们构建到目标文件中。然后,你可以将这些目标文件链入你为X64平台写的C++代码中。这是克服缺少x64内联汇编器的一种方法(意思就是说克服C++编译器不能直接编译.asm后缀的汇编语言源文件的方法,目前还没有内联支持直接编译汇编语言源文件)。
2. 具体步骤
2.1 第一步:按Visual Studio向导建立C++工程,下面重点是第二步。
2.2 第二步:将汇编语言源文件加入C++工程中。
2.2.1 选中解决方法下面的C++工程,在右键弹出的上下菜单中, 选中Build Customizations(构建自定义)。
2.2.2 在Visual C++ 构建自定文件对话框中,勾选 masm(.targets,.props)这一项,然后确定退出,如下图所示:
2.2.3 选中解决方法下面的C++工程,在右键弹出的上下菜单中,选择 Add(添加), 再选 Add New Item(添加新项)。
2.2.4 在面板上选择C++ file (.cpp),以你想添加成的名字命名一个新文件,注意,扩展名写的.asm,替代C++的默认扩展名.cpp,点确定完成新建汇编源文件。
这个时候,如果我们右键观察新建的汇编语言汇文件,可以看到如图所示的选项:
通过这些操作之后,当你构建你的解决方案时,系统将调用MASM汇编器将.asm文件编译进目标文件中,然后再链入你的C++工程中。为了使访问符号文件理容易,将你的汇编函数在你的C++代码中用为extern "C"声明, 而不是在你的汇编语言源文件中使用C++的函数名修饰约定方法声明你的汇编函数。
例如,汇编语言文件中是这样:
;test.asm
.code
IntegerAddSub proc
mov eax,ecx ;eax = a
add eax,edx ;eax = a + b
add eax,r8d ;eax = a + b + c
sub eax,r9d ;eax = a + b + c - d
ret ;return result to caller
IntegerAddSub endp
end;
C++中调用:
/*声明为 extern "C" */
extern "C" int IntegerAddSub(int a, int b, int c, int d);
static void PrintResult(const char* msg, int a, int b, int c, int d, int result)
{
const char nl = '\n';
cout << msg << nl;
cout << "a = " << a << nl;
cout << "b = " << b << nl;
cout << "c = " << c << nl;
cout << "d = " << d << nl;
cout << "result = " << result << nl;
cout << nl;
}
//调用:
int _tmain(int argc, _TCHAR* argv[])
{
int a, b, c, d, result;
a = 10; b = 20; c = 30; d = 18;
result = IntegerAddSub(a, b, c, d);
PrintResult("Test 1", a, b, c, d, result);
a = 101; b = 34; c = -190; d = 25;
result = IntegerAddSub(a, b, c, d);
PrintResult("Test 2", a, b, c, d, result);
system("pause");
return 0;
}
来自微软官方文档: