In the source code of the go language, you will find many things. The code only has function signatures, but cannot see the function body, such as:
// src/os/ 68 linesfunc runtime_beforeExit() // implemented in runtime
Here we only see the function signature, but we can't see the function body. We searched the globally and found that its function body is definedsrc/runtime/
middle
// os_beforeExit is called from (0). //go:linkname os_beforeExit os.runtime_beforeExit func os_beforeExit() { if raceenabled { racefini() } }
It connects the function signature and the function body through go:linkname. So, can we implement this in the code? Since it can be used in library functions, can we also use it in our own code structure? The following experiments will implement this usage step by step
Create a 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
Writing test code
$cd hello // Function signature$vim package hello import ( _ "demo/link" ) func Hello() // Function body$vim package link import _ "unsafe" //go:linkname helloWorld demo/ func helloWorld() { println("hello world!") }
Execute code
$cd demo vim package main import ( "demo/hello" ) func main() { () }
Compile and run
go run # demo/hello hello/:7:6: missing function body
The assembly file label added in the hello folder can be executed through compilation
$cd hello && touch $go run hello world!
Summarize
The above is the usage of linkname in go language introduced to you by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support for my website!
If you think this article is helpful to you, please reprint it. Please indicate the source, thank you!