---
title: "go语言工程约定，分包和编译"
author: "lavafree"
date: "2012-09-22T00:09:51Z"
tags: []
categories: ["编程语言"]
slug: "go"
draft: false
lastmod: "2012-09-22T00:09:51Z"
id: 1683363
url: "https://lavafree.iteye.com/blog/1683363"
---

go-lang已经发布了go1，前段时间看了一下go语言的教程，就喜欢上了这门语言，但使用多个文件编译是碰到一些麻烦，引用出错编译通不过，google之找到了这篇教程https://golang.org/doc/code.html，我按自己的理解记录一下，英文好的童鞋还是看原文吧！

go语言可以用makefile，也可以按他的约定来直接编译。约定其实比较简单，go语言是这么来配置他的工程的

```
prjDir						# 工程根目录
	bin/					
		hello              	# 可执行文件，window下为hello.exe
	pkg/					# 包跟目录
		linux_amd64/ 		# 执行平台
			example/		# 分包目录
				newmath.a  	# 包，类似java中的jar
	src/					# 源代码
		example/			
			hello/			# 类似于java的example.hello，java中是包内部目录，go则在包外部
				hello.go   	# 命令行，这个必须在main包，有main函数，生成名字为hello
			newmath/		# 包名，将位于example，编译生成newmath.a包
				sqrt.go    	# 包内源代码文件，不包含main函数
```

 

 

如上结构是go的目录结构了，其实bin和pkg是不用自己建立的，go编译自动生成。

实战一下：

1.在d:\\workspace下新建prjDir目录

2.设置GOPATH环境变量

GOPATH = d:\\workspace\\prjDir

3.prjDir下新建src

4.src下新建example，旗下新建newmath及sqrt.go文件

5.sqrt.go文件输入代码

```
// Package newmath is a trivial example package.
package newmath

// Sqrt returns an approximation to the square root of x.
func Sqrt(x float64) float64 {
        // This is a terrible implementation.
        // Real code should import "math" and use math.Sqrt.
        z := 0.0
        for i := 0; i < 1000; i++ {
                z -= (z*z - x) / (2 * x)
        }
        return z
}
```

 

6.example下新建hello,旗下新建hello.go

7.hello.go输入

 

```
// Hello is a trivial example of a main package.
package main

import (
        "example/newmath"
        "fmt"
)

func main() {
        fmt.Printf("Hello, world.  Sqrt(2) = %v\n", newmath.Sqrt(2))
}
```

 

8.命令行切换到src下，输入命令

go install example/newmath

这时候根prjDir下生成一个pkg,内容如上图

9.src下输入命令

go install example/hello

编译生成hello（hello.exe）命令行

10.执行./hello(hello.exe)就有输出了

go的这种约定很简洁，其实GOROOT就相当于（JAVA\_HOME）

GOPATH 相当于PATH，依赖路径，可以配置多个，linux用冒号（:）隔开，window用分号（;）

GO的引用是  一级包/二级包/包名 比如example/newmath