自从您提出这个问题以来,这可能已经发生了变化,但目前,安装Xcode 命令行工具 https://developer.apple.com/download/more/(安装 Xcode 后)安装NASM
(网络汇编器)和GASM
(GNU 汇编器)。要开始在汇编中进行编码,您有几个选项,具体取决于您正在执行的操作:即在 Xcode 中构建,或使用以下命令在终端中构建NASM
or GASM
直接地。
Xcode 9.4.1
如果您想使用 IDE,您可以通过单击“文件 > 新文件”将程序集文件添加到 Xcode 中,然后搜索“程序集”,您将看到程序集文件类型。或者,您可以添加一个空白文件,然后从文件检查器的“类型”下拉列表中手动选择文件类型。除非您的应用程序需要 Cocoa 框架,否则您应该在项目/目标创建期间创建命令行应用程序而不是 Cocoa 应用程序。作为示例命令行程序:
hello.asm(来自参考文献中列出的教程站点):
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
主要.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()
如果您希望使用 C 而不是 Swift 进行汇编操作,则需要创建头文件而不是使用@_silgen_name
:
#ifndef Bridging_Header_h
#define Bridging_Header_h
const char *start(void);
#endif /* Bridging-Header_h */
Assembly Build Rule
您还必须为目标提供“构建规则”,这一点很重要。为此:
- 单击项目导航器中的项目图标
- 在目标列表中选择适当的目标
- 单击“构建规则”选项卡
- 在搜索栏中搜索 NASM
- 单击“复制到目标”,并确保“进程”设置为“NASM 程序集文件”,“使用”设置为“自定义脚本”
- 在下面的“自定义脚本”部分中,输入以下命令(确保路径指向yourNASM 汇编器):
/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 的符号”的编译器错误至关重要。
Terminal
如果您不介意,或者可能更喜欢在终端中工作,您可以使用您选择的文本编辑器(vim
, nano
, and emacs
内置于终端中,TextEdit 内置于 macOS 中)来创建程序集文件。然后使用nasm
or gasm
用于组装文件的命令。类型man nasm
or man gasm
为您提供各种可用的选项。
参考:
汇编代码示例 -你好.asm http://cs.lmu.edu/~ray/notes/nasmtutorial/
从 Swift 或 C 引用程序集(需要桥接头)-丹尼尔·特兰 https://stackoverflow.com/a/39421006/3928158
构建规则 -公制熊猫 https://metricpanda.com/compiling-nasm-with-xcode-in-a-cpp-project