是否可以在GO代码中包含内联汇编?
This blog post显示将GO编译到单独的.s
文件并对其进行编辑,而不是像许多C编译器支持的那样将inline ASM作为GO函数的一部分.
是否可以在GO代码中包含内联汇编?
This blog post显示将GO编译到单独的.s
文件并对其进行编辑,而不是像许多C编译器支持的那样将inline ASM作为GO函数的一部分.
它不支持内联汇编,但您可以通过C、用CGO编译并使用import "C"
来链接用汇编语言编写的代码,就像在gmp.go中一样.您也可以编写与GO直接兼容的汇编样式,如asm_linux_amd64.s中,它要求函数名称以"·"开头.
或者,您可以使用NASM和gccgo,这是我到目前为止最喜欢的方式.(请注意,Nasm似乎不支持以"·"开头的函数).
下面是一个有效的"hello world"示例:
你好asm:
; Based on hello.asm from nasm
SECTION .data ; data section
msg: db "Hello World",10 ; the string to print, 10=cr
len: equ $-msg ; "$" means "here"
; len is a value, not an address
SECTION .text ; code section
global go.main.hello ; make label available to linker (Go)
go.main.hello:
; --- setup stack frame
push rbp ; save old base pointer
mov rbp,rsp ; use stack pointer as new base pointer
; --- print message
mov edx,len ; arg3, length of string to print
mov ecx,msg ; arg2, pointer to string
mov ebx,1 ; arg1, where to write, screen
mov eax,4 ; write sysout command to int 80 hex
int 0x80 ; interrupt 80 hex, call kernel
; --- takedown stack frame
mov rsp,rbp ; use base pointer as new stack pointer
pop rbp ; get the old base pointer
; --- return
mov rax,0 ; error code 0, normal, no error
ret ; return
主要的开始:
package main
func hello();
func main() {
hello()
hello()
}
还有一个方便的Makefile:
main: main.go hello.o
gccgo hello.o main.go -o main
hello.o: hello.asm
nasm -f elf64 -o hello.o hello.asm
clean:
rm -rf _obj *.o *~ *.6 *.gch a.out main
我在main.go中调用了两次hello()
,只是为了再次判断hello()是否正确返回.
请注意,在Linux上直接调用中断80h并不被认为是一种好的风格,而调用用C编写的函数更多的是"future 证明".还要注意的是,这是专门针对64位Linux的汇编,并且在任何方式、形状或形式上都不是独立于平台的.
我知道这不是对你问题的直接回答,但这是我所知道的在GO中使用汇编的最简单的方法,因为没有内联.如果您确实需要内联,可以编写一个脚本,从源文件中提取内联程序集,并按照上述模式进行准备.够近了吗?:)
Go、C和Nasm的快速示例:gonasm.tgz
Update:更高版本的gccgo需要-g标志,只需要"main.hello"而不是"go.main.hello".下面是Go、C和Yasm:goyasm.tgz的更新示例