Инструменты Go

Вопросы написания собственного программного кода (на любых языках)

Модератор: Olej

Аватара пользователя
Olej
Писатель
Сообщения: 21338
Зарегистрирован: 24 сен 2011, 14:22
Откуда: Харьков
Контактная информация:

Re: Go

Непрочитанное сообщение Olej » 01 июн 2016, 13:10

Olej писал(а): Самое время доустановить и плагин Go из комплекта проекта GCC:
...
С этим нужно разбираться что там с ним происходит в Fedora 23!
Страница "всё относительно gccgo" ;-) на сайте golang.org : Setting up and using gccgo

Собственно, о каких-либо несовместимостях с GCC 5.X там ничего нет:
The GCC 5 releases include a complete implementation of the Go 1.4 user libraries. The Go 1.4 runtime is not fully merged, but that should not be visible to Go programs.

Аватара пользователя
Olej
Писатель
Сообщения: 21338
Зарегистрирован: 24 сен 2011, 14:22
Откуда: Харьков
Контактная информация:

Re: Go

Непрочитанное сообщение Olej » 01 июн 2016, 13:27

Olej писал(а): Собственно, о каких-либо несовместимостях с GCC 5.X там ничего нет:
До установки gccgo:

Код: Выделить всё

[olej@dell tasks]$ go build -compiler gccgo hello.go
go build command-line-arguments: : fork/exec : no such file or directory
[olej@dell tasks]$ go build -compiler gc hello.go
[olej@dell tasks]$ file hello
hello: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), statically linked, not stripped
[olej@dell tasks]$ ls -l hello
-rwxr-xr-x. 1 olej olej 2367424 июн  1 13:12 hello

Код: Выделить всё

[olej@dell tasks]$ go env
GOARCH="amd64"
GOBIN=""
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOOS="linux"
GOPATH="/home/olej/2016_WORK/GoBook"
GORACE=""
GOROOT="/usr/lib/golang"
GOTOOLDIR="/usr/lib/golang/pkg/tool/linux_amd64"
GO15VENDOREXPERIMENT=""
CC="gcc"
GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0"
CXX="g++"
CGO_ENABLED="1"
Устанавливаем gccgo:

Код: Выделить всё

[olej@dell ~]$ sudo dnf install gcc-go
...
Установлено:
  gcc-go.x86_64 5.3.1-6.fc23                    libgo.x86_64 5.3.1-6.fc23                    libgo-devel.x86_64 5.3.1-6.fc23
Выполнено!
Повторяем сборку:

Код: Выделить всё

[olej@dell tasks]$ go build -compiler gc hello.go  
hello.go:10:8: cannot find package "fmt" in any of:
	/usr/src/fmt (from $GOROOT)
	/home/olej/2016_WORK/GoBook/src/fmt (from $GOPATH)
package runtime: cannot find package "runtime" in any of:
	/usr/src/runtime (from $GOROOT)
	/home/olej/2016_WORK/GoBook/src/runtime (from $GOPATH)
[olej@dell tasks]$ go build -compiler gccgo hello.go  
# command-line-arguments
ar: `u' modifier ignored since `D' is the default (see `U')
[olej@dell tasks]$ file hello
hello: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 2.6.32, BuildID[sha1]=24bd1519714ce69e26d279a1bbf35ddcf2de8021, not stripped
[olej@dell tasks]$ ls -l hello
-rwxrwxr-x. 1 olej olej 32400 июн  1 13:19 hello
[olej@dell tasks]$ ./hello
Hello, 世界
И переменные окружения GO:

Код: Выделить всё

[olej@dell tasks]$ go env
GOARCH="amd64"
GOBIN=""
GOCHAR="6"
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOOS="linux"
GOPATH="/home/olej/2016_WORK/GoBook"
GORACE=""
GOROOT="/usr"
GOTOOLDIR="/usr/libexec/gcc/x86_64-redhat-linux/5.3.1"
CC="/usr/bin/gcc"
GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0"
CXX="/usr/bin/g++"
CGO_ENABLED="1"
Видно что уплыли GOROOT и GOTOOLDIR, да и состав переменных окружения GO поменялся ... и работа GoLang разрушилась :-o

Аватара пользователя
Olej
Писатель
Сообщения: 21338
Зарегистрирован: 24 сен 2011, 14:22
Откуда: Харьков
Контактная информация:

Re: Go

Непрочитанное сообщение Olej » 01 июн 2016, 13:36

Olej писал(а): Видно что уплыли GOROOT и GOTOOLDIR, да и состав переменных окружения GO поменялся ... и работа GoLang разрушилась :-o
Так что лучшее, что пока можно сделать :-( :

Код: Выделить всё

[olej@dell tasks]$ sudo dnf remove gcc-go
...
Удалено:
  gcc-go.x86_64 5.3.1-6.fc23                        libgo.x86_64 5.3.1-6.fc23                        libgo-devel.x86_64 5.3.1-6.fc23                       
Выполнено!

Код: Выделить всё

[olej@dell tasks]$ go build -compiler gc hello.go
[olej@dell tasks]$ file hello
hello: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), statically linked, not stripped
[olej@dell tasks]$ ./hello
Hello, 世界

Код: Выделить всё

[olej@dell tasks]$ go env
GOARCH="amd64"
GOBIN=""
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOOS="linux"
GOPATH="/home/olej/2016_WORK/GoBook"
GORACE=""
GOROOT="/usr/lib/golang"
GOTOOLDIR="/usr/lib/golang/pkg/tool/linux_amd64"
GO15VENDOREXPERIMENT=""
CC="gcc"
GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0"
CXX="g++"
CGO_ENABLED="1"

Аватара пользователя
Olej
Писатель
Сообщения: 21338
Зарегистрирован: 24 сен 2011, 14:22
Откуда: Харьков
Контактная информация:

Re: Go

Непрочитанное сообщение Olej » 01 июн 2016, 16:41

Olej писал(а): Вот так! :-o - то, что так успешно работало в полтора года назад - развалилось! :cry:
Не может быть вызван компилятор 6g по именам, унаследованным из ОС Plan 9:
С этим удалось разобраться ... просмотрев что происходит ещё на 2-х компьютерах с установленными GoLang, соответственно, версиями 1.2 и 1.4

Код: Выделить всё

olej@nvidia ~ $ lsb_release -ircd
Distributor ID: LinuxMint
Description:    Linux Mint 17.1 Rebecca
Release:        17.1
Codename:       rebecca

Код: Выделить всё

olej@nvidia ~ $ go version
go version go1.2.1 linux/386
olej@nvidia ~/2016_WORK/in.WORK/GO $ go env
GOARCH="386"
GOBIN=""
GOCHAR="8"
GOEXE=""
GOHOSTARCH="386"
GOHOSTOS="linux"
GOOS="linux"
GOPATH=""
GORACE=""
GOROOT="/usr/lib/go"
GOTOOLDIR="/usr/lib/go/pkg/tool/linux_386"
TERM="dumb"
CC="gcc"
GOGCCFLAGS="-g -O2 -fPIC -m32 -pthread"
CXX="g++"
CGO_ENABLED="1"

Код: Выделить всё

olej@nvidia ~ $ ls -l /usr/lib/go/pkg/tool/linux_386/
итого 22496
-rwxr-xr-x 1 root root  276171 марта 20  2014 5a
-rwxr-xr-x 1 root root  789355 марта 20  2014 5c
-rwxr-xr-x 1 root root 1608694 марта 20  2014 5g
-rwxr-xr-x 1 root root  821570 марта 20  2014 5l
-rwxr-xr-x 1 root root  312581 марта 20  2014 6a
-rwxr-xr-x 1 root root  871601 марта 20  2014 6c
-rwxr-xr-x 1 root root 1651410 марта 20  2014 6g
-rwxr-xr-x 1 root root  913713 марта 20  2014 6l
-rwxr-xr-x 1 root root  302731 марта 20  2014 8a
-rwxr-xr-x 1 root root  913628 марта 20  2014 8c
-rwxr-xr-x 1 root root 1673377 марта 20  2014 8g
-rwxr-xr-x 1 root root  859426 марта 20  2014 8l
-rwxr-xr-x 1 root root  408364 марта 20  2014 addr2line
-rwxr-xr-x 1 root root 4486432 марта 20  2014 cgo
-rwxr-xr-x 1 root root   67332 марта 20  2014 dist
-rwxr-xr-x 1 root root 3419232 марта 20  2014 fix
-rwxr-xr-x 1 root root  336897 марта 20  2014 nm
-rwxr-xr-x 1 root root  416614 марта 20  2014 objdump
-rwxr-xr-x 1 root root  298469 марта 20  2014 pack
-rwxr-xr-x 1 root root  157784 марта 20  2014 pprof
-rwxr-xr-x 1 root root 2409192 марта 20  2014 yacc

Код: Выделить всё

olej@nvidia ~/2016_WORK/in.WORK/GO/gorun $ go build -compiler gccgo gorun.go
olej@nvidia ~/2016_WORK/in.WORK/GO/gorun $ sudo cp gorun /usr/local/bin
olej@nvidia ~/2016_WORK/in.WORK/GO/gorun $ which gorun
/usr/local/bin/gorun
Испытываем:

Код: Выделить всё

olej@nvidia ~/2016_WORK/in.WORK/GO $ cat rtiny.go
#!/usr/local/bin/gorun

package main
import ( "fmt" )

func main() {
   fmt.Println( "минимальное приложение" )
}

olej@nvidia ~/2016_WORK/in.WORK/GO $ time ./rtiny.go
минимальное приложение
real    0m0.278s
user    0m0.232s
sys     0m0.028s

olej@nvidia ~/2016_WORK/in.WORK/GO $ time ./rtiny.go
минимальное приложение
real    0m0.023s
user    0m0.012s
sys     0m0.008s

Аватара пользователя
Olej
Писатель
Сообщения: 21338
Зарегистрирован: 24 сен 2011, 14:22
Откуда: Харьков
Контактная информация:

Re: Go

Непрочитанное сообщение Olej » 01 июн 2016, 16:51

Olej писал(а): С этим удалось разобраться ... просмотрев что происходит ещё на 2-х компьютерах с установленными GoLang, соответственно, версиями 1.2 и 1.4
А теперь возвращаемся к версии 1.5:

Код: Выделить всё

[olej@dell golang]$ lsb_release -ircd
Distributor ID:	Fedora
Description:	Fedora release 23 (Twenty Three)
Release:	23
Codename:	TwentyThree
[olej@dell golang]$ go version
go version go1.5.4 linux/amd64

Код: Выделить всё

[olej@dell golang]$ go env
GOARCH="amd64"
GOBIN=""
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOOS="linux"
GOPATH="/home/olej/2016_WORK/GoBook"
GORACE=""
GOROOT="/usr/lib/golang"
GOTOOLDIR="/usr/lib/golang/pkg/tool/linux_amd64"
GO15VENDOREXPERIMENT=""
CC="gcc"
GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0"
CXX="g++"
CGO_ENABLED="1"
Смотрим GOROOT

Код: Выделить всё

[olej@dell linux_amd64]$ pwd
/usr/lib/golang/pkg/tool/linux_amd64
[olej@dell linux_amd64]$ ls
addr2line  api  asm  cgo  compile  cover  dist  doc  fix  link  nm  objdump  pack  pprof  trace  vet  yacc
[olej@dell linux_amd64]$ ./compile -V
6g version go1.5.4
Они просто переименовали традиционные имена (6g, 8g, 5g) идущие от Plan 9.
Восстановим имена:

Код: Выделить всё

[olej@dell linux_amd64]$ sudo ln -s compile 6g
[sudo] пароль для olej:
[olej@dell tasks]$ time ./rtiny.go 
go tool: no such tool "6l"
error: failed to run go: exit status 3
real	0m0.039s
user	0m0.027s
sys	0m0.018s
Теперь ему нет 6l:

Код: Выделить всё

[olej@dell linux_amd64]$ pwd
/usr/lib/golang/pkg/tool/linux_amd64
[olej@dell linux_amd64]$ ./link -V
./link: version go1.5.4
[olej@dell linux_amd64]$ sudo ln -s link 6l
[olej@dell tasks]$ time ./rtiny.go
минимальное приложение
real    0m0.500s
user    0m0.707s
sys     0m0.054s
[olej@dell tasks]$ time ./rtiny.go
минимальное приложение
real    0m0.003s
user    0m0.001s
sys     0m0.003s
Ну вот и всё ... разобрались :
- первый запуск исполнимого исходного кода Go, с компиляцией, потребовал 0.5 сек.
- все последующие его запуски - 0.003 сек. (больше чем в 100 раз быстрее)

Аватара пользователя
Olej
Писатель
Сообщения: 21338
Зарегистрирован: 24 сен 2011, 14:22
Откуда: Харьков
Контактная информация:

Re: Go

Непрочитанное сообщение Olej » 01 июн 2016, 17:24

Форматирование (автоформатирование) файла исходного кода Go (какого конкретно файла кода здесь не имеет значения) ...
До:

Код: Выделить всё

package main

import "fmt"

func main() {
   const (
      _ = 1 << ( 10 * iota )
      KiB // 1024
      MiB // 1048576
      GiB // 1073741824
      TiB // 1099511627776 ( > 1<<32 )
      PiB // 1125299906242624
      EiB // 1152921504606846976
      ZiB // 1180591620717411303424 ( > 1<<64 )
      YiB // 1208925819614629174706176
        )
   fmt.Printf( "%d\n%d\n%d\n%d\n%d\n%d\n",
                   KiB, MiB, GiB, TiB, PiB, EiB )
   fmt.Printf( "%.0f\n%.0f\n", float64( ZiB ), float64( YiB ) )
}
Выполнение:

Код: Выделить всё

[olej@dell tasks]$ go fmt iota_p105.go 
iota_p105.go
После:

Код: Выделить всё

package main

import "fmt"

func main() {
        const (
                _   = 1 << (10 * iota)
                KiB // 1024
                MiB // 1048576
                GiB // 1073741824
                TiB // 1099511627776 ( > 1<<32 )
                PiB // 1125299906242624
                EiB // 1152921504606846976
                ZiB // 1180591620717411303424 ( > 1<<64 )
                YiB // 1208925819614629174706176
        )
        fmt.Printf("%d\n%d\n%d\n%d\n%d\n%d\n",
                KiB, MiB, GiB, TiB, PiB, EiB)
        fmt.Printf("%.0f\n%.0f\n", float64(ZiB), float64(YiB))
}
Вложения
iota_p105.go
(429 байт) 199 скачиваний

Аватара пользователя
Olej
Писатель
Сообщения: 21338
Зарегистрирован: 24 сен 2011, 14:22
Откуда: Харьков
Контактная информация:

Re: Go

Непрочитанное сообщение Olej » 01 июн 2016, 23:56

Olej писал(а):
Olej писал(а):styles/abbcode/images/code.gif
Самое время доустановить и плагин Go из комплекта проекта GCC:
...
С этим нужно разбираться что там с ним происходит в Fedora 23!
Собственно, о каких-либо несовместимостях с GCC 5.X там ничего нет:
Любопытно, что именно при переходе от 1.4 к 1.5 произошли большие изменения - Go 1.5 Release Notes, самое интересное:
The compiler and runtime are now implemented in Go and assembler, without C. The only C source left in the tree is related to testing or to cgo.
Now that the Go compiler and runtime are implemented in Go, a Go compiler must be available to compile the distribution from source. Thus, to build the Go core, a working Go distribution must already be in place. (Go programmers who do not work on the core are unaffected by this change.) Any Go 1.4 or later distribution (including gccgo) will serve.
The suites of programs that were the compilers (6g, 8g, etc.), the assemblers (6a, 8a, etc.), and the linkers (6l, 8l, etc.) have each been consolidated into a single tool that is configured by the environment variables GOOS and GOARCH. The old names are gone; the new tools are available through the go tool mechanism as go tool compile, go tool asm, and go tool link. Also, the file suffixes .6, .8, etc. for the intermediate object files are also gone; now they are just plain .o files.
As described above, the compiler in Go 1.5 is a single Go program, translated from the old C source, that replaces 6g, 8g, and so on. Its target is configured by the environment variables GOOS and GOARCH.
Go 1.5 Bootstrap Plan
Go 1.5 will use a toolchain written in Go (at least in part).
...
We have been planning for a year now to eliminate all C programs from the Go source tree. The C compilers (5c, 6c, 8c, 9c) have already been removed. The remaining C programs will be converted to Go: they are the Go compilers (golang.org/s/go13compiler), the assemblers, the linkers (golang.org/s/go13linker), and cmd/dist.

Аватара пользователя
Olej
Писатель
Сообщения: 21338
Зарегистрирован: 24 сен 2011, 14:22
Откуда: Харьков
Контактная информация:

Re: Go

Непрочитанное сообщение Olej » 02 июн 2016, 09:24

Olej писал(а):Небольшая GoLang страничка для онлайновой компиляции и изучения работы кода на языке Go:
The Go Playground
Результаты работы онлайнового Go может несколько отличаться - к этому нужно быть готовым:

The Go Playground
iota_p105.png
http://ideone.com/Ia1bHY
iota_p105_2.png

Аватара пользователя
Olej
Писатель
Сообщения: 21338
Зарегистрирован: 24 сен 2011, 14:22
Откуда: Харьков
Контактная информация:

Re: Go

Непрочитанное сообщение Olej » 02 июн 2016, 13:16

Olej писал(а): Так что лучшее, что пока можно сделать :-( :

Код: Выделить всё

[olej@dell tasks]$ sudo dnf remove gcc-go
...
Удалено:
  gcc-go.x86_64 5.3.1-6.fc23                        libgo.x86_64 5.3.1-6.fc23                        libgo-devel.x86_64 5.3.1-6.fc23                       
Выполнено!
И с этим тоже удалось разобраться:
- это всё-таки баг сборки gcc-go в Fedora 23 ... или может и в других дистрибутивах, или вообще gcc-go
- gcc-go при установке, если ссылка /etc/alternatives/go уже установлена в /usr/lib/golang/bin/go (т.е. golang уже установлен) не должен её переписывать, устанавливать в /usr/bin/go.gcc
- ... должен создавать ссылку только если её нет
- ... а он это делает тупо в любом случае
- а golang при установке (после gcc-go) ссылку не переписывает
- ну и то же самое с ссылкой /etc/alternatives/gofmt

Теперь это легко поправить, делаем (я показываю это на 32-бит Fedora 23 - пути!):

Код: Выделить всё

[root@localhost alternatives]# cd /etc/alternatives
[root@localhost alternatives]# mv go go.gcc
[root@localhost alternatives]# mv gofmt gofmt.gcc
[root@localhost alternatives]# ln -s /usr/lib/golang/bin/go go
[root@localhost alternatives]# ln -s /usr/lib/golang/bin/gofmt gofmt
И теперь всё работает не мешая друг другу:

Код: Выделить всё

[olej@localhost GO]$ go build -compiler gc -o tiny.gc tiny.go
[olej@localhost GO]$ go build -compiler gccgo -o tiny.gcc tiny.go
# command-line-arguments
ar: `u' modifier ignored since `D' is the default (see `U')
[olej@localhost GO]$ ls -l tiny.*
-rwxr-xr-x. 1 olej olej 1905168 Jun  2 12:54 tiny.gc
-rwxr-xr-x. 1 olej olej   25528 Jun  2 12:55 tiny.gcc
-rw-r--r--. 1 olej olej     111 Jun  1 14:23 tiny.go

Код: Выделить всё

[olej@localhost GO]$ file tiny.*
tiny.gc:  ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), statically linked, not stripped
tiny.gcc: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked, interpreter /lib/ld-linux.so.2, for GNU/Linux 2.6.32, BuildID[sha1]=ceea47622da1118f6a98e3febfc687fc80a0d9b2, not stripped
tiny.go:  C source, UTF-8 Unicode text
[olej@localhost GO]$ ./tiny.gc
минимальное приложение
[olej@localhost GO]$ ./tiny.gcc
минимальное приложение

Аватара пользователя
Olej
Писатель
Сообщения: 21338
Зарегистрирован: 24 сен 2011, 14:22
Откуда: Харьков
Контактная информация:

Re: Go

Непрочитанное сообщение Olej » 02 июн 2016, 13:23

Olej писал(а): И теперь всё работает не мешая друг другу:
Фу-у-ух ... камень с души! :-P
Это, может, и не так принципиально для большинства пользователей, но несовместимое поведение golang & gcc-go означало бы, что что-то поменяли в идеологии разработки Go ... а так это всего лишь нахомутали в сборке дистрибутива.

Ответить

Вернуться в «Программирование»

Кто сейчас на конференции

Сейчас этот форум просматривают: нет зарегистрированных пользователей и 4 гостя