This post is going to talk about Makefiles, and as a backend developer, mastering Makefiles coffee can help you sip more. Coming back to the book

Golang has a lot of Go Commands built in to help us with every stage of GO development, but there are a lot of times we need to share our code with others, and people who are seeing our code engineering for the first time may not know how to make it work. Of course, you can also use readme. md or other methods to inform readers.

But for those who just want to build programs quickly, using makefiles is a nice way to abstract away the technical details. When we see makefiles, we naturally think of making or making Install to build programs. Bid farewell to the memory of the long string of commands crazy keyboard occasionally also wrong embarrassing scene 😅

Such as:

go build -o hello hello.go./hello
Copy the code

Using makefiles, we can easily customize a target to accomplish this task

.PHONY: buildandrunBIN_FILE=hello​buildandrun:        @go build -o "${BIN_FILE}" hello.go        ./"${BIN_FILE}"
Copy the code

Then we can finish our work with the following command

make./"hello"hello world​
Copy the code

When we actually go live and build compile-time the command might look something like this:

go install -tags="${BUILD_TAGS}" -ldflags "-X version.version=$(VERSION) -X version.date=$(DATE) -X version.commit=$(COMMIT) -X version.branch=$(BRANCH) -w -s" -gcflags=all="-N -l " ./...
Copy the code

To assemble the Makefile, we just type four characters make, and we have to do different things at different stages of development,

  • Clean up and compile intermediate object files

  • Run the test case

  • Check test coverage

  • Perform code checks and so on

The Goal mechanism for makefiles abstractions this situation nicely, and here is the configuration of makefiles in my work, which is not too complicated but really useful.

.PHONY: all build clean run check cover lint docker helpBIN_FILE=helloall: check buildbuild: @go build -o "${BIN_FILE}"clean: go clean rm --force "xx.out"test: go testcheck: go fmt ./ go vet ./cover: go test -coverprofile xx.out go tool cover -html=xx.outrun: ./"${BIN_FILE}"lint: golangci-lint run --enable-alldocker: @docker build -t leo/hello:latest .help: @echo "make format go code and build binary "@echo "make build build go code and build binary" @echo "make clean intermediate target file "@echo "make test execute test case" @echo "make check format go code "@echo "make cover check test coverage" @echo "make run run the program directly "@echo "make lint executes code to check" @echo "make Docker build Docker image"Copy the code

conclusion

Using Makefiles to manage the build of our program reduces the amount of typing and spelling errors and simplifies building projects. Live online environments are better with CI/CD, so if you haven’t tried makefiles yet, you can.