Willis
Willis

Reputation: 777

VS Code Code Runner cannot run multi Go files

For example, I have a simple project called demo:

demo
├── go.mod
├── main.go
└── sum.go

Here is the code, for go.mod, you can run go mod init under demo directory to generate automatically (but you can create in yourself too):

// main.go
package main

import "fmt"

func main() {
    num3 := sum(1, 2)
    fmt.Println(num3)
}

// sum.go
package main

func sum(num1 int, num2 int) int {
    return num1 + num2
}

// go.mod
module demo

go 1.17

Now in main.go file, right click mouse → Run Code, that means you will run main.go with Code Runner, but it will print an error

# command-line-arguments
demo/main.go:6:10: undefined: sum

The reason for this error is that Code Runner only runs the main.go file, if we cd to demo path in the Terminal and run go run ., the code can run very well.

How can we solve this problem?

Upvotes: 1

Views: 1527

Answers (1)

Willis
Willis

Reputation: 777

If we want to run the code with Code Runner, we should add some configs that will let the Code Runner cd into the target folder and then run go run ..

Open VS Code Settings page, click "Open Settings (JSON)" button on the top right corner: enter image description here

NOTE: in the newer versions of VS Code this dedicated button is gone, use the Command Palette like described in the official documentation.

Add the following config to the settings.json file:

"code-runner.executorMap": {
    "go": "cd $dir && go run .",
},
"code-runner.executorMapByGlob": {
    "$dir/*.go": "go"
},

Be aware that the settings.json may already have "code-runner.executorMapByFileExtension", but this is not the same with "code-runner.executorMap", do not add "go": "cd $dir && go run .", to "code-runner.executorMapByFileExtension".

After adding this configurations, now you can run your Go code with Code Runner (you don't need to restart or reload VS Code).

Upvotes: 4

Related Questions