Search code examples
govisual-studio-codevscode-debugger

in vscode how to provide compilation command with specific file names


I am trying to debug the following code in vscode. I have 2 versions of the file in the same directory, with minor differences (temp edits during debugging). So I now have 3 files in the directory: go.mod, bug1.go, and bug2.go.

//bug1.go
package main

import (
    "fmt"
)

type Animal int64

const (
    Goat Animal = iota
    Cat
)

func (n Animal) String() string {
    switch n {
    case Goat:
        return "Goat"
    case Cat:
        return "Cat"
    }
    return "?"
}

type Group struct {
    A, B Animal
}

func main() {

    fmt.Println("Animal: ", Cat)
}

I can run the above code from command line like this (which only compiles bug1.go and ignores bug2.go):

go run bug1.go

Now I am trying to debug bug1.go, using the following launch.json:

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Launch",
      "type": "go",
      "request": "launch",
      "mode": "auto",
      "program": "${workspaceFolder}",
      "env": {},
      "args": []
    }
  ]
}

So I opened bug1.go in vscode, and pressed Run and Debug, and then I am seeing errors being reported from bug2.go. Looks like vscode is trying to compile all the files in the directory together, and is detecting code duplications:

Build Error: go build -o /Users/.../bug/__debug_bin -gcflags all=-N -l .
./bug2.go:9:6: Animal redeclared in this block
    ./bug1.go:9:6: other declaration of Animal
./bug2.go:12:5: Goat redeclared in this block
    ./bug1.go:12:5: other declaration of Goat

How do I configure vscode to compile only bug1.go and ignore bug2.go?


Solution

  • Set program to ${file}:

    {
        "version": "0.2.0",
        "configurations": [
            {
                "name": "Launch current file",
                "type": "go",
                "request": "launch",
                "mode": "auto",
                "program": "${file}"
            }
        ]
    }
    
    • program: Path to the program folder (or any go file within that folder) when in debug or test mode, and to the pre-built binary file to debug in exec mode. If it is not an absolute path, the extension interpretes it as a workspace relative path.

      (Default: "${workspaceFolder}")

      See Launch.json attributes

    • ${file}: the current opened file

      see Variables Reference