一方面是 Go 语言编译后的可执行文件大小比 C 语言的大很多,
另一方面是 C 语言的可执行文件需要依赖 glibc 动态库,
用 ldd 命令可以看出来:
或者直接删除 glibc 动态库, C 可执行程序报错,而 Go 的还能运行:
这时候只有内部命令可以运行,外部命令,包括 ln 甚至最常用的 ls 命令也不能运行了:
设置好 LD_PRELOAD 环境变量之后, ln 命令可以运行,但是 sudo 仍然不能运行
只能靠 root 用户来重新创建软连接了:
所以用 sudo 来 rm 文件要小心,还是用 root 比较好。如果没有预先留一个打开的 root 终端,登录都登不进去。
golang中没有类似C语言中条件编译的写法,比如在C代码中可以使用如下语法做一些条件编译,结合宏定义来使用可以实现诸如按需编译release和debug版本代码的需求
build tags 是通过代码注释的形式实现的,要写在文件的最顶端;
go build指令在编译项目的时候会检查每一个文件的build tags,用来决定是编译还是跳过该文件
build tags遵循以下规则
示例:
约束此文件只能在支持kqueue的BSD系统上编译
一个文件可能包含多行条件编译注释,比如:
约束该文件在linux/386 或 darwin/386平台编译
需要注意的点
正确的写法如下:
编译方法:
具有_$GOOS.go后缀的go文件在编译的时候会根据当前平台来判断是否将该文件导入并编译;同样适用于处理器架构判断 _$GOARCH.go。
两者可以结合起来使用,形式为: _$GOOS_$GOARCH.go
示例:
文件名必须提供,如果只由后缀的文件名会被编译器忽略,比如:
这两个文件会被编译器忽略,因为以下划线开头的文件都会被忽略
1、解压压缩包到go工作目录,如解压到E:\opensource\go\go,解压后的目录结构如下:
E:\opensource\go\go
├─api
├─bin
│ ├─go.exe
│ ├─godoc.exe
│ └─gofmt.exe
├─doc
├─include
├─lib
├─misc
├─pkg
├─src
└─test
2、增加环境变量GOROOT,取值为上面的go工作目录
3、Path环境变量中添加"%GOROOT%\bin",以便能够直接调用go命令来编译go代码,至此go编译环境就配置好了
注:如果不想手动设置系统环境变量,也可下载go启动环境批处理附件,
修改goenv.bat文件中的GOROOT值为上面的go工作目录后直接双击该bat文件,go编译环境变量即设置完成。
4、测试go编译环境,启动一个cmd窗口,直接输入go,看到下面的提示就是搭建成功了
E:\opensource\go\go>go
Go is a tool for managing Go source code.
Usage:
go command [arguments]
The commands are:
build compile packages and dependencies
clean remove object files
doc run godoc on package sources
env print Go environment information
fix run go tool fix on packages
fmt run gofmt on package sources
get download and install packages and dependencies
install compile and install packages and dependencies
listlist packages
run compile and run Go program
testtest packages
toolrun specified go tool
version print Go version
vet run go tool vet on packages
Use "go help [command]" for more information about a command.
Additional help topics:
gopath GOPATH environment variable
packagesdescription of package lists
remote remote import path syntax
testflagdescription of testing flags
testfuncdescription of testing functions
Use "go help [topic]" for more information about that topic.
5、编译helloworld测试程序,go语言包中test目录带有helloworld.go测试程序,源码见"附一 helloworld.go",
直接调用"go build helloworld.go"就生成了"helloworld.exe"可执行程序,运行一下这个程序看到了我们期望的hello,wolrd。
E:\opensource\go\go\test>go build helloworld.go
E:\opensource\go\go\test>helloworld.exe
hello, world
E:\opensource\go\go\test>
附一 helloworld.go
// cmpout
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Test that we can do page 1 of the C book.
package main
func main() {
print("hello, world\n")
}