如何在Xcode中用汇编语言编写和构建程序?
我搜索了一下,但没有成功。你能帮我吗?如果不能在xcode中编写NASM代码,请推荐一些好的IDE。
自从您提出这个问题以来,这可能已经发生了变化,但目前,安装Xcode命令行工具(在安装Xcode之后)会安装NASM
(Netwide Assembler)和GASM
(GNU Assemble)。要在程序集中开始编码,您有两个选项,具体取决于您正在执行的操作:即,在Xcode中构建,或者直接使用NASM
或GASM
在Terminal中构建。
Xcode 9.4.1
如果你想使用IDE,你可以通过点击"文件>新建文件",然后搜索"程序集",将程序集文件添加到Xcode中,你会看到一个程序集文件类型。或者,您可以添加一个空白文件,然后从文件检查器的"类型"下拉菜单中手动选择文件类型。除非你的应用程序需要一个Cocoa框架,否则你应该在项目/目标创建期间创建一个命令行应用程序,而不是Cocoa应用程序。例如命令行程序:
hello.am(来自参考资料中列出的教程网站):
global _start
section .text
_start: mov rax, 0x02000004 ; system call for write
mov rdi, 1 ; file handle 1 is stdout
mov rsi, message ; address of string to output
mov rdx, 13 ; number of bytes
syscall ; invoke operating system to do the write
mov rax, 0x02000001 ; system call for exit
xor rdi, rdi ; exit code 0
syscall ; invoke operating system to exit
section .data
message: db "Hello, World", 10 ; note the newline at the end
main.swift:
import Foundation
// Generate a "name" for the assembler operation that may be used
// as a Swift function.
@_silgen_name("start") func start() -> String
// Create a fake struct to use our function. We return 0 so that we
// can call `variable()` below without any warnings (because we're
// we're setting something).
struct Test {
func variable() -> Int32 {
print(start())
return 0
}
}
// Declare a test instance and call `variable`. `x` is merely acting
// as a placeholder so we can call variable and not get warnings for
// this test example.
let x = Test().variable()
如果您希望在Assembly操作中使用C而不是Swift,则需要创建头文件,而不是使用@_silgen_name
:
#ifndef Bridging_Header_h
#define Bridging_Header_h
const char *start(void);
#endif /* Bridging-Header_h */
程序集生成规则重要的是,您还应为目标提供一个"构建规则"。为此:
- 单击项目导航器中的项目图标
- 在目标列表中选择适当的目标
- 单击"生成规则"选项卡
- 在搜索字段中搜索NASM
- 单击"复制到目标",确保"Process"设置为"NASM assembly files","Using"设为"Custom script"
- 在下面的"自定义脚本"部分中,键入以下命令(确保路径指向您的NASM汇编程序的位置):
/usr/local/bin/nasm -f macho64 ${INPUT_FILE_PATH} -o ${SCRIPT_OUTPUT_FILE_0}
这是一个终端命令——要了解更多信息,请在终端中键入man nasm
- 然后单击"输出文件"部分的加号并添加以下内容:
$(DERIVED_FILE_DIR)/${INPUT_FILE_BASE}.o
此生成规则对于避免编译器错误"找不到体系结构x86_64的符号"至关重要。
终端
如果您不介意,或者可能更喜欢在终端中工作,您可以使用您选择的文本编辑器(vim
、nano
和emacs
内置在终端中,TextEdit内置在macOS中)来创建程序集文件。然后使用nasm
或gasm
命令来组装文件。键入man nasm
或man gasm
以获取可用的各种选项。
参考文献:
程序集代码示例-hello.asm
引用Swift或C中的程序集(需要桥接头)-Daniel Tran
构建规则-公制Panda
我的2美分用于Xcode 11 AND内联(主要用于教学…)
无需外部工具:
int main(int argc, const char * argv[]) {
long long test = 0;
asm
{
mov rax, test
inc rax
inc rax
inc rax
mov test, rax
}
printf("Hello, World! %lldn", test);
return 0;
}