oftewel
oftewel

Reputation: 221

multi package makefile example for go

I'm trying to setup a multi package go project something like

./main.go

./subpackage1/sub1_1.go

./subpackage1/sub1_2.go

./subpackage2/sub2_1.go

./subpackage2/sub2_2.go

where main.go imports both subpackage1 and subpackage2. And subpackage2 imports subpackage1.

Ive been looking around for go makefile examples but I can't find anything that supports this kind of set-up. Any idea?

Upvotes: 22

Views: 10443

Answers (4)

thejoshwolfe
thejoshwolfe

Reputation: 5504

Check out https://github.com/banthar/Go-SDL which is an actively maintained multi-package go project using Makefiles.

I notice some of these the answers use the obsolete Make.$(GOARCH) include. So hopefully the above link will be stabler than trying to stay on top of Google's changing API in an answer here.

Upvotes: 4

Jeff Connelly
Jeff Connelly

Reputation: 171

Install godag then run:

gd -o myapp

It will automatically build a Directed Acyclic Graph (DAG) of all the dependencies in your src/ directory, then compile and link each package in the proper order.

Much easier than manually maintaining a Makefile, especially since $(GOROOT)/src/Make.* has changed in recent versions of Go (there is no longer a Make.$(GOARCH)). Also useful:

gd clean removes object files.

gd -test runs your automated tests (see testing package).

gd -dot=myapp.dot generates a graph of your package imports you can visualize using GraphViz.

Upvotes: 17

Scott Wales
Scott Wales

Reputation: 11686

Something like this should work

# Makefile
include $(GOROOT)/src/Make.$(GOARCH)
all:main
main:main.$O
    $(LD) -Lsubpackage1/_obj -Lsubpackage2/_obj -o $@ $^
%.$O:%.go  subpackage1 subpackage2
    $(GC) -Isubpackage1/_obj -Isubpackage2/_obj -o $@ $^
subpackage1:
    $(MAKE) -C subpackage1
subpackage2:
    $(MAKE) -C subpackage2
.PHONY:subpackage1 subpackage2

# subpackage1/Makefile
TARG=subpackage1
GOFILES=sub1_1.go sub1_2.go
include $(GOROOT)/src/Make.$(GOARCH)
include $(GOROOT)/src/Make.pkg

# subpackage2/Makefile
TARG=subpackage2
GOFILES=sub2_1.go sub2_2.go
include $(GOROOT)/src/Make.$(GOARCH)
include $(GOROOT)/src/Make.pkg
GC+=-I../subpackage1/_obj
LD+=-L../subpackage1/_obj
sub2_1.$O sub2_2.$O:subpackage1
subpackage1:
    $(MAKE) -C ../subpackage1
.PHONY:subpackage1

If you don't install the subpackages you need to explicitly set the include path. The supplied makefile Make.pkg is mainly to build packages, which is why it's only included in the subpackage makefile.

Upvotes: 7

ppierre
ppierre

Reputation: 188

hello world with a Makefile and a test (Googles Groupes : golang-nuts)

Upvotes: 5

Related Questions