46

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

4
  • 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. Commented Jan 22, 2014 at 20:19
  • 1
    they all three have package main. Commented Jan 22, 2014 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. Commented Jan 22, 2014 at 21:25
  • 2
    You can build and execute easily without go run: "go build && ./packagename" Commented Jan 23, 2014 at 11:12

3 Answers 3

67

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.

Sign up to request clarification or add additional context in comments.

6 Comments

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.
@RoelVanNyen That's not weird at all - since they're imported, the go toolchain knows where to look for them
Would be great though if the companion packages were imported automatically by go run
@RoelVanNyen Why didn't you suggest go run *.go?
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
|
44

You could execute it as:

go run .

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

Comments

3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.