单文件编译

先上 hello world 代码,保存为 helloworld.go

  1. package main
  2. import "fmt"
  3. func main() {
  4. fmt.Println("Hello World!")
  5. }
  1. $go build helloworld.go

生成 helloworld.exe, 文件名和源码文件名一直。 也可以加上 -o 参数, 指定要生成的可执行文件名。比如:

  1. $go build -o hello helloworld.go
  2. Jesson@LAPTOP-QJ5P400E MINGW64 /e/mygitee/go-learn/blog (master)
  3. $ ls
  4. hello* helloworld.exe* helloworld.go
  5. Jesson@LAPTOP-QJ5P400E MINGW64 /e/mygitee/go-learn/blog (master)
  6. $ ./hello
  7. Hello World!
  8. Jesson@LAPTOP-QJ5P400E MINGW64 /e/mygitee/go-learn/blog (master)
  9. $

如果想看更多 go build 的参数的话, 可以直接在命令行输入 go help build

  1. $ go help build
  2. usage: go build [-o output] [-i] [build flags] [packages]
  3. Build compiles the packages named by the import paths,
  4. along with their dependencies, but it does not install the results.
  5. If the arguments to build are a list of .go files from a single directory,
  6. build treats them as a list of source files specifying a single package.
  7. When compiling packages, build ignores files that end in '_test.go'.
  8. When compiling a single main package, build writes
  9. the resulting executable to an output file named after
  10. the first source file ('go build ed.go rx.go' writes 'ed' or 'ed.exe')
  11. or the source code directory ('go build unix/sam' writes 'sam' or 'sam.exe').
  12. The '.exe' suffix is added when writing a Windows executable.
  13. When compiling multiple packages or a single non-main package,
  14. build compiles the packages but discards the resulting object,
  15. serving only as a check that the packages can be built.
  16. The -o flag forces build to write the resulting executable or object
  17. to the named output file or directory, instead of the default behavior described
  18. in the last two paragraphs. If the named output is a directory that exists,
  19. then any resulting executables will be written to that directory.
  20. The -i flag installs the packages that are dependencies of the target.
  21. The build flags are shared by the build, clean, get, install, list, run,
  22. and test commands:
  23. -a
  24. force rebuilding of packages that are already up-to-date.
  25. -n
  26. print the commands but do not run them.
  27. -p n
  28. the number of programs, such as build commands or
  29. test binaries, that can be run in parallel.
  30. The default is the number of CPUs available.
  31. -race
  32. enable data race detection.
  33. Supported only on linux/amd64, freebsd/amd64, darwin/amd64, windows/amd64,
  34. linux/ppc64le and linux/arm64 (only for 48-bit VMA).
  35. -msan
  36. enable interoperation with memory sanitizer.
  37. Supported only on linux/amd64, linux/arm64
  38. and only with Clang/LLVM as the host C compiler.
  39. On linux/arm64, pie build mode will be used.
  40. -v
  41. print the names of packages as they are compiled.
  42. -work
  43. print the name of the temporary work directory and
  44. do not delete it when exiting.
  45. -x
  46. print the commands.
  47. -asmflags '[pattern=]arg list'
  48. arguments to pass on each go tool asm invocation.
  49. -buildmode mode
  50. build mode to use. See 'go help buildmode' for more.
  51. -compiler name
  52. name of compiler to use, as in runtime.Compiler (gccgo or gc).
  53. -gccgoflags '[pattern=]arg list'
  54. arguments to pass on each gccgo compiler/linker invocation.
  55. -gcflags '[pattern=]arg list'
  56. arguments to pass on each go tool compile invocation.
  57. -installsuffix suffix
  58. a suffix to use in the name of the package installation directory,
  59. in order to keep output separate from default builds.
  60. If using the -race flag, the install suffix is automatically set to race
  61. or, if set explicitly, has _race appended to it. Likewise for the -msan
  62. flag. Using a -buildmode option that requires non-default compile flags
  63. has a similar effect.
  64. -ldflags '[pattern=]arg list'
  65. arguments to pass on each go tool link invocation.
  66. -linkshared
  67. build code that will be linked against shared libraries previously
  68. created with -buildmode=shared.
  69. -mod mode
  70. module download mode to use: readonly, vendor, or mod.
  71. See 'go help modules' for more.
  72. -modcacherw
  73. leave newly-created directories in the module cache read-write
  74. instead of making them read-only.
  75. -modfile file
  76. in module aware mode, read (and possibly write) an alternate go.mod
  77. file instead of the one in the module root directory. A file named
  78. "go.mod" must still be present in order to determine the module root
  79. directory, but it is not accessed. When -modfile is specified, an
  80. alternate go.sum file is also used: its path is derived from the
  81. -modfile flag by trimming the ".mod" extension and appending ".sum".
  82. -pkgdir dir
  83. install and load all packages from dir instead of the usual locations.
  84. For example, when building with a non-standard configuration,
  85. use -pkgdir to keep generated packages in a separate location.
  86. -tags tag,list
  87. a comma-separated list of build tags to consider satisfied during the
  88. build. For more information about build tags, see the description of
  89. build constraints in the documentation for the go/build package.
  90. (Earlier versions of Go used a space-separated list, and that form
  91. is deprecated but still recognized.)
  92. -trimpath
  93. remove all file system paths from the resulting executable.
  94. Instead of absolute file system paths, the recorded file names
  95. will begin with either "go" (for the standard library),
  96. or a module path@version (when using modules),
  97. or a plain import path (when using GOPATH).
  98. -toolexec 'cmd args'
  99. a program to use to invoke toolchain programs like vet and asm.
  100. For example, instead of running asm, the go command will run
  101. 'cmd args /path/to/asm <arguments for asm>'.
  102. The -asmflags, -gccgoflags, -gcflags, and -ldflags flags accept a
  103. space-separated list of arguments to pass to an underlying tool
  104. during the build. To embed spaces in an element in the list, surround
  105. it with either single or double quotes. The argument list may be
  106. preceded by a package pattern and an equal sign, which restricts
  107. the use of that argument list to the building of packages matching
  108. that pattern (see 'go help packages' for a description of package
  109. patterns). Without a pattern, the argument list applies only to the
  110. packages named on the command line. The flags may be repeated
  111. with different patterns in order to specify different arguments for
  112. different sets of packages. If a package matches patterns given in
  113. multiple flags, the latest match on the command line wins.
  114. For example, 'go build -gcflags=-S fmt' prints the disassembly
  115. only for package fmt, while 'go build -gcflags=all=-S fmt'
  116. prints the disassembly for fmt and all its dependencies.
  117. For more about specifying packages, see 'go help packages'.
  118. For more about where packages and binaries are installed,
  119. run 'go help gopath'.
  120. For more about calling between Go and C/C++, run 'go help c'.
  121. Note: Build adheres to certain conventions such as those described
  122. by 'go help gopath'. Not all projects can follow these conventions,
  123. however. Installations that have their own conventions or that use
  124. a separate software build system may choose to use lower-level
  125. invocations such as 'go tool compile' and 'go tool link' to avoid
  126. some of the overheads and design decisions of the build tool.
  127. See also: go install, go get, go clean.

后面用到再分享其他参数。
新增一个文件 calc.go 文件,增加一个求和的函数,同时 main.go 中增加这个函数的调用。

  1. // calc.go
  2. package main
  3. func sum(a int, b int) int {
  4. return a + b
  5. }
  6. //helloworld.go
  7. package main
  8. import "fmt"
  9. func main() {
  10. fmt.Println("Hello World!")
  11. fmt.Println(sum(10, 20))
  12. }

编译方式如下 go build helloworld.go calc.go

  1. $ go build helloworld.go calc.go
  2. Jesson@LAPTOP-QJ5P400E MINGW64 /e/mygitee/go-learn/blog (master)
  3. $ ./helloworld.exe
  4. Hello World!
  5. 30

上面这种情况,适合学习的时候写点简短的代码, 并不适合构建大型项目。

多文件多模块编译

实际工作中,往往只有一个 main.go ,然后其他函数和功能都放在包里面,那么这种情况下,该如何进行编译?这里以一个计算包,一个main.go 为例。
文件目录结构如下:main.go 和 calc 文件夹在同一目录。

image.png

  1. // add.go
  2. package calc
  3. func Add(a int, b int) int {
  4. return a + b
  5. }
  1. // sub.go
  2. package calc
  3. func Sub(a int, b int) int {
  4. return a - b
  5. }
  1. package main
  2. import "fmt"
  3. import "calc"
  4. func main() {
  5. fmt.Println("Hello!")
  6. fmt.Println(calc.Add(10, 20), calc.Sub(20, 10))
  7. fmt.Println("Bye bye!")
  8. }
  1. Jesson@LAPTOP-QJ5P400E MINGW64 /e/mygitee/go-learn/blog/src (master)
  2. $ go build main.go
  3. Jesson@LAPTOP-QJ5P400E MINGW64 /e/mygitee/go-learn/blog/src (master)
  4. $ ./main.exe
  5. Hello!
  6. 30 10
  7. Bye bye!

如果报错,可以 export GO111MODULE=off 关闭 go module
export GOPATH= /e/mygitee/go-learn/blog/ 指定工程目录
如果增加新的模块, 只需要建个新文件,和calc 同级目录,到此,基本的工程项目目录构建的差不多了。

go module

go1.11 之后引入了 go module。 通过 go env 命令,可以看到有个变量 GO111MODULE 变量。

在上面代码结构基础上,先用 go mod init 初始化一个mod 文件。

  1. $ go mod init blog
  2. go: creating new go.mod: module blog
  3. Jesson@LAPTOP-QJ5P400E MINGW64 /e/mygitee/go-learn/blog/src (master)
  4. $ go build
  5. Jesson@LAPTOP-QJ5P400E MINGW64 /e/mygitee/go-learn/blog/src (master)
  6. $ ls
  7. blog.exe* calc/ go.mod main.go xxx.exe*
  8. Jesson@LAPTOP-QJ5P400E MINGW64 /e/mygitee/go-learn/blog/src (master)
  9. $

这样 main.go 中的引用 calc 包的路径,要做点改动, 改为 import”blog/calc”