go build命令做了些什么工作?
2018-08-13 本文已影响0人
沙漠中的猴
简介
大家都知道可以使用go build
命令编译go文件。可是他都为你做了什么,你了解吗?
解析
// 建立临时的工作目录
WORK=/tmp/go-build479912431
mkdir -p $WORK/b001/
// 定义一些配置文件,比如一些你所引用的包的位置等内容
cat >$WORK/b001/importcfg << 'EOF' # internal
# import config
packagefile fmt=/usr/local/go1.10.3/pkg/linux_amd64/fmt.a
packagefile runtime=/usr/local/go1.10.3/pkg/linux_amd64/runtime.a
EOF
// 然后进入你的工作目录,使用编译器来编译你的源代码。中间会涉及到很多编译开关
cd /root/go/src
/usr/local/go1.10.3/pkg/tool/linux_amd64/compile -o $WORK/b001/_pkg_.a -trimpath $WORK/b001 -p main -complete -buildid Lu9L7drt9vSF5dvhI8GP/Lu9L7drt9vSF5dvhI8GP -goversion go1.10.3 -D _/root/go/src -importcfg $WORK/b001/importcfg -pack -c=2 ./main.go
// 将编译生成的.a文件打上一个标签
/usr/local/go1.10.3/pkg/tool/linux_amd64/buildid -w $WORK/b001/_pkg_.a # internal
// 将你编译的文件放到缓存目录。
cp $WORK/b001/_pkg_.a /root/.cache/go-build/61/617a485226ff759f1f4327a29fa9106a82ea4f19ce06a328e890587957ed457d-d # internal
// 将你接下来要用到的内容,放到配置文件中。
cat >$WORK/b001/importcfg.link << 'EOF' # internal
packagefile _/root/go/src=$WORK/b001/_pkg_.a
packagefile fmt=/usr/local/go1.10.3/pkg/linux_amd64/fmt.a
packagefile runtime=/usr/local/go1.10.3/pkg/linux_amd64/runtime.a
packagefile errors=/usr/local/go1.10.3/pkg/linux_amd64/errors.a
packagefile io=/usr/local/go1.10.3/pkg/linux_amd64/io.a
packagefile math=/usr/local/go1.10.3/pkg/linux_amd64/math.a
packagefile os=/usr/local/go1.10.3/pkg/linux_amd64/os.a
packagefile reflect=/usr/local/go1.10.3/pkg/linux_amd64/reflect.a
packagefile strconv=/usr/local/go1.10.3/pkg/linux_amd64/strconv.a
packagefile sync=/usr/local/go1.10.3/pkg/linux_amd64/sync.a
packagefile unicode/utf8=/usr/local/go1.10.3/pkg/linux_amd64/unicode/utf8.a
packagefile runtime/internal/atomic=/usr/local/go1.10.3/pkg/linux_amd64/runtime/internal/atomic.a
packagefile runtime/internal/sys=/usr/local/go1.10.3/pkg/linux_amd64/runtime/internal/sys.a
packagefile sync/atomic=/usr/local/go1.10.3/pkg/linux_amd64/sync/atomic.a
packagefile internal/cpu=/usr/local/go1.10.3/pkg/linux_amd64/internal/cpu.a
packagefile internal/poll=/usr/local/go1.10.3/pkg/linux_amd64/internal/poll.a
packagefile internal/testlog=/usr/local/go1.10.3/pkg/linux_amd64/internal/testlog.a
packagefile syscall=/usr/local/go1.10.3/pkg/linux_amd64/syscall.a
packagefile time=/usr/local/go1.10.3/pkg/linux_amd64/time.a
packagefile unicode=/usr/local/go1.10.3/pkg/linux_amd64/unicode.a
packagefile internal/race=/usr/local/go1.10.3/pkg/linux_amd64/internal/race.a
EOF
// 新建一个临时文件
mkdir -p $WORK/b001/exe/
cd .
// 使用链接器将相关的内容链接到a.out文件中,这个是最终的可执行文件
/usr/local/go1.10.3/pkg/tool/linux_amd64/link -o $WORK/b001/exe/a.out -importcfg $WORK/b001/importcfg.link -buildmode=exe -buildid=fCZ2BwjJQHDh8r605eLL/Lu9L7drt9vSF5dvhI8GP/yO3Oy45Zmann5-s74imm/fCZ2BwjJQHDh8r605eLL -extld=gcc $WORK/b001/_pkg_.a
// 打一个标签
/usr/local/go1.10.3/pkg/tool/linux_amd64/buildid -w $WORK/b001/exe/a.out # internal
// 将生成的可执行文件复制到你的当前目录
cp $WORK/b001/exe/a.out src
// 删除临时目录
rm -r $WORK/b001/