Skip to content
Latchkey

Go "//go:linkname must refer to declared function" - Fix in CI

//go:linkname aliases a local symbol to one in another package, often an unexported runtime symbol. It is fragile: it needs import "unsafe", the target must exist, and newer Go releases restrict linkname access - any of which can break a build that relied on it.

What this error means

A build fails with //go:linkname must refer to declared function or variable, //go:linkname requires import "unsafe", or a linker error that the linknamed symbol is missing. It commonly breaks after a Go upgrade that moved or locked down the target symbol.

go build output
./hack.go:10:1: //go:linkname must refer to declared function or variable
# or, after a toolchain upgrade:
link: github.com/org/app: reference to undefined symbol runtime.nanotime1

Common causes

Missing import "unsafe" or a missing local declaration

//go:linkname requires import "unsafe" in the file and a matching local function/variable declaration to attach to; without both, the directive is rejected.

The target symbol moved or was restricted

A newer Go release renamed, removed, or locked down the runtime/internal symbol the linkname pointed at, so the link fails.

How to fix it

Provide the unsafe import and a local declaration

Add import "unsafe" and declare the local symbol the linkname binds.

Go
import _ "unsafe"

//go:linkname nanotime runtime.nanotime
func nanotime() int64

Stop relying on the internal symbol

  1. Check whether a public API now covers what the linkname reached for.
  2. Replace the linkname with the supported API where one exists.
  3. If you must keep it, pin the Go version whose symbol your linkname targets.

How to prevent it

  • Avoid //go:linkname into runtime/internal symbols where possible.
  • Keep import "unsafe" and a local declaration alongside every linkname.
  • Re-test linkname code on each Go toolchain upgrade.

Frequently asked questions

What causes ""//go:linkname" errors"?
//go:linkname requires import "unsafe" in the file and a matching local function/variable declaration to attach to; without both, the directive is rejected.
How do I fix "//go:linkname" errors?
Add import "unsafe" and declare the local symbol the linkname binds.

Related guides

References

Latchkey auto-heals failures like this one - detected, fixed, and retried without you. Start free → 30-day trial · No credit card