42

I have a few files in the main package under one directory:

main.go config.go server.go

When I do: "go build" the program builds perfect and runs fine. When I do: "go run main.go" it fails.

Output:

# command-line-arguments
./main.go:7: undefined: Config
./main.go:8: undefined: Server

The symbols that are undefined are structs and they are capitalised so should be exported.

My Go version: go1.1.2 linux/amd64

Roel Van Nyen
  • 1,279
  • 1
  • 9
  • 19
  • What is the `package` for `main.go` and `config.go` with `server.go`? If you are going to run them all three must have `package main`. – Kavu Jan 22 '14 at 20:19
  • 1
    they all three have package main. – Roel Van Nyen Jan 22 '14 at 21:00
  • 2
    Keep in mind that `go run` is fairly limited. You should be using `go build` to build your package(s) and running it with ./packagename or packagename if it's on your PATH. – elithrar Jan 22 '14 at 21:25
  • 2
    You can build and execute easily without go run: "go build && ./packagename" – Matthias Jan 23 '14 at 11:12

3 Answers3

58

This should work

go run main.go config.go server.go

Go run takes a file or files and it complies those and only those files which explains the missing symbols in the original post.

Nick Craig-Wood
  • 52,955
  • 12
  • 126
  • 132
  • This indeed works but the wierd thing is that external imports (the ones you put in import()) do work perfectly without me having to specify them on the command line. – Roel Van Nyen Jan 22 '14 at 21:01
  • 3
    @RoelVanNyen That's not weird at all - since they're imported, the go toolchain knows where to look for them – Cubic Jan 22 '14 at 21:16
  • 1
    Would be great though if the companion packages were imported automatically by go run – Ian Lewis Feb 27 '14 at 16:31
  • 1
    @RoelVanNyen Why didn't you suggest `go run *.go`? – Gianfranco Reppucci Oct 17 '17 at 15:24
  • @RoelVanNyen This seems better -if has no side effects at all. All in all, why to write down each and every thing. – vahdet Dec 09 '17 at 10:46
  • 1
    There is a side effect for me: `$ go run *.go` `go run: cannot run *_test.go files (main_test.go)` There's a discussion around this [here](https://stackoverflow.com/questions/23695448/golang-run-all-go-files-within-current-directory-through-the-command-line-mul) – cody Aug 30 '18 at 13:50
33

You could execute it as:

go run .

so you don't have to include all files manually.

Daniel Pecos
  • 481
  • 5
  • 5
1

Good practise would be to create a package for it and run

go run ./app

Ex. Folder Structure

    ├──app/
    |  ├──main.go
    |  ├──config.go
    |  ├──server.go
    ├──bin/
    |  ├──foo.go
    └──pkg/
       └──bar.go
Piyush Bag
  • 81
  • 2
  • 11