Is it possible to include inline assembly in Go code?
This blog post shows compiling Go to a separate .s file and editing it, but not inline asm as part of a Go function like many C compilers support.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
There is no support for inline assembly, but you can link with code written in assembly through C, compiling with cgo and using
import "C", like in gmp.go. You could alternatively write in a style of assembly that is directly compatible with Go, like in asm_linux_amd64.s, that requires that function names start with “·”.Or, you can use nasm and gccgo, my favorite way so far. (Note that Nasm does not seem to support functions starting with “·”).
Here’s a working “hello world” example:
hello.asm:
main.go:
And a handy Makefile:
I call
hello()twice in main.go, just to double check that hello() returns properly.Note that calling interrupt 80h directly is not considered good style on Linux, and calling functions written is C is more “future proof”. Also note that this is assembly specifically for 64-bit Linux, and is not platform-independent in any way, shape or form.
I know it’s not a direct answer to your question, but it’s the easiest route I know for using assembly with Go, in lack of inlining. If you really need inlining, it’s possible to write a script that extracts inline assembly from source files and prepares it in a way that follows the pattern above. Close enough? 🙂
Quick example for Go, C and Nasm: gonasm.tgz
Update: Later versions of gccgo needs the -g flag and only “main.hello” is needed instead of “go.main.hello”. Here is an updated example for Go, C and Yasm: goyasm.tgz