Undefined reference to <variable/function> error in Golang

In Golang, the "undefined reference to <variable/function>" error occurs when you reference a variable or function that has not been defined or declared. This error indicates that the compiler or linker is unable to find the definition of the variable or function that you are referencing.

Let's consider an example to understand this error. Consider the following Golang program:

Example

package main

import "fmt"

func main() {
    message := "Hello, World!"
    printMessage(message)
}

func printMessage(str string) {
    fmt.Println(str)
}

In this program, we declare a variable message and initialize it with the value "Hello, World!". We then call a function printMessage and pass message as an argument to the function.

However, when we try to compile and run this program, we will encounter the following error:

Output

./main.go:7:2: undefined reference to printMessage

This error occurs because we are referencing the printMessage function before it has been declared or defined. To fix this error, we need to declare or define the function before it is used, like this:


Example

package main

import "fmt"

func printMessage(str string) {
    fmt.Println(str)
}

func main() {
    message := "Hello, World!"
    printMessage(message)
}

In this modified program, we define the printMessage function before it is called in the main function. This code will compile and run without any errors.

In summary, the "undefined reference to <variable/function>" error in Golang occurs when you reference a variable or function that has not been defined or declared. To fix this error, the developer needs to declare or define the variable or function before it is used.


Most Helpful This Week