In the source code of the go language, you will find a lot of codes that only have function signatures, but you cannot see the function body, such as :
// src/os/proc.go 68行 func runtime_beforeExit() // implemented in runtime
Here we only see the function signature, but not the function body. After searching globally, we found that its function body is defined in src/runtime/proc.go
// os_beforeExit is called from os.Exit(0). //go:linkname os_beforeExit os.runtime_beforeExit func os_beforeExit() { if raceenabled { racefini() } }
It connects the function signature and function body through go:linkname. So can we implement this in code? Since this can be used in library functions, can it also be used in our own code structure? The following is an experimental method to implement such usage step by step
Create project directory
$mkdir demo && cd demo
go mod initialize project directory
$go mod init demo
Create function signature pkg and function body pkg
$mkdir hello $mkdir link
Write test code
$cd hello // 函数签名 $vim hello.go package hello import ( _ "demo/link" ) func Hello() // 函数体 $vim link.go package link import _ "unsafe" //go:linkname helloWorld demo/hello.Hello func helloWorld() { println("hello world!") }
Execute code
$cd demo vim demo.go package main import ( "demo/hello" ) func main() { hello.Hello() }
Compile and run
go run demo.go # demo/hello hello/hello.go:7:6: missing function body
Add the assembly file mark of aa.s in the hello folder, then you can compile and execute
$cd hello && touch aa.s $go run demo.go hello world!