Building a plugin
- Go course
- Advanced
- Lesson 20/68
- 4 min
Learn to build a plugin with go build -buildmode=plugin.
Building a plugin
A plugin is a package with package main that doesn't need a main function. Every exported (upper-case) function and variable becomes a symbol of the plugin.
// selam/selam.go
package main
func Selam(ad string) string { return "Merhaba " + ad }Build: go build -buildmode=plugin -o selam.so ./selam
Version matching
The safest way to build the main program and the plugin with the same module versions is to keep them in the same repository or share the same go.mod. Loading a plugin built differently gives the error "plugin was built with a different version of package".
Practice Write a plugin function
Add the function func Ikiye(n int) int to the code that will be built as a plugin (it returns twice n). In main, print fmt.Println(Ikiye(21)) as a test.
Starter code
package main
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
import "fmt"
func Ikiye(n int) int { return n * 2 }
func main() {
fmt.Println(Ikiye(21))
}Expected output
42
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which flag is needed to build a plugin?
- -o plugin
- -buildmode=plugin Correct answer
- -plugin
- -shared=true
Explanation: go build -buildmode=plugin produces a shared object (.so); -o sets the file name.
2 Build command
go build ____ -o selam.so ./selam
go build -buildmode=plugin -o selam.so ./selam
Explanation: -buildmode=plugin makes the output a loadable .so file.
3 Plugin source
| Term | Meaning |
|---|---|
package main |
Plugin package name |
func Selam |
Exported symbol |
func yardimci |
Hidden (lower case) |
-o selam.so |
Output file |