cборка приложений Go

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

Модератор: Olej

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

cборка приложений Go

Непрочитанное сообщение Olej » 11 май 2017, 17:55

Перенесен сюда вопрос из другого обсуждения:
Как собрать статически слинкованную (staticaly linked) программу на GO, использующую библиотеки Tcl/Tk ? Чтобы команда Unix "ldd" при проверке исполняемого файла программы не выдавала никаких ссылок на динамические библиотеки, а команда "file" сообщала о приложении как о "staticaly linked".

Аватара пользователя
perseus
Писатель
Сообщения: 99
Зарегистрирован: 11 май 2017, 18:01
Откуда: Щёлково, Московская обл.
Контактная информация:

Re: cборка приложений Go

Непрочитанное сообщение perseus » 11 май 2017, 22:40

Я нашел какой-то вариант ответа на этот вопрос в интернете: blog.ralch.com/tutorial/golang-sharing-libraries
но на практике мне его реализовать не удаётся - команда go install -buildmode=shared -linkshared std ругается, что флаг -buildmode не определён, чертовщина какая-то !

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

Re: cборка приложений Go

Непрочитанное сообщение Olej » 11 май 2017, 22:55

perseus писал(а):Я нашел какой-то вариант ответа на этот вопрос в интернете: blog.ralch.com/tutorial/golang-sharing-libraries
но на практике мне его реализовать не удаётся - команда go install -buildmode=shared -linkshared std ругается, что флаг -buildmode не определён, чертовщина какая-то !
Начинать нужно с версии Golang

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

[olej@dell ~]$ go version
go version go1.5.4 linux/amd64
В зависимости от версий очень сильно менялись возможности сборки:

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

[olej@dell ~]$ go help install
usage: go install [build flags] [packages]

Install compiles and installs the packages named by the import paths,
along with their dependencies.

For more about the build flags, see 'go help build'.
For more about specifying packages, see 'go help packages'.

See also: go build, go get, go clean.

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

[olej@dell ~]$ go help build
usage: go build [-o output] [-i] [build flags] [packages]

Build compiles the packages named by the import paths,
along with their dependencies, but it does not install the results.

If the arguments to build are a list of .go files, build treats
them as a list of source files specifying a single package.

When compiling a single main package, build writes
the resulting executable to an output file named after
the first source file ('go build ed.go rx.go' writes 'ed' or 'ed.exe')
or the source code directory ('go build unix/sam' writes 'sam' or 'sam.exe').
The '.exe' suffix is added when writing a Windows executable.

When compiling multiple packages or a single non-main package,
build compiles the packages but discards the resulting object,
serving only as a check that the packages can be built.

The -o flag, only allowed when compiling a single package,
forces build to write the resulting executable or object
to the named output file, instead of the default behavior described
in the last two paragraphs.

The -i flag installs the packages that are dependencies of the target.

The build flags are shared by the build, clean, get, install, list, run,
and test commands:

	-a
		force rebuilding of packages that are already up-to-date.
	-n
		print the commands but do not run them.
	-p n
		the number of builds that can be run in parallel.
		The default is the number of CPUs available, except
		on darwin/arm which defaults to 1.
	-race
		enable data race detection.
		Supported only on linux/amd64, freebsd/amd64, darwin/amd64 and windows/amd64.
	-v
		print the names of packages as they are compiled.
	-work
		print the name of the temporary work directory and
		do not delete it when exiting.
	-x
		print the commands.

	-asmflags 'flag list'
		arguments to pass on each go tool asm invocation.
	-buildmode mode
		build mode to use. See 'go help buildmode' for more.
	-compiler name
		name of compiler to use, as in runtime.Compiler (gccgo or gc).
	-gccgoflags 'arg list'
		arguments to pass on each gccgo compiler/linker invocation.
	-gcflags 'arg list'
		arguments to pass on each go tool compile invocation.
	-installsuffix suffix
		a suffix to use in the name of the package installation directory,
		in order to keep output separate from default builds.
		If using the -race flag, the install suffix is automatically set to race
		or, if set explicitly, has _race appended to it.  Using a -buildmode
		option that requires non-default compile flags has a similar effect.
	-ldflags 'flag list'
		arguments to pass on each go tool link invocation.
	-linkshared
		link against shared libraries previously created with
		-buildmode=shared
	-pkgdir dir
		install and load all packages from dir instead of the usual locations.
		For example, when building with a non-standard configuration,
		use -pkgdir to keep generated packages in a separate location.
	-tags 'tag list'
		a list of build tags to consider satisfied during the build.
		For more information about build tags, see the description of
		build constraints in the documentation for the go/build package.
	-toolexec 'cmd args'
		a program to use to invoke toolchain programs like vet and asm.
		For example, instead of running asm, the go command will run
		'cmd args /path/to/asm <arguments for asm>'.

The list flags accept a space-separated list of strings. To embed spaces
in an element in the list, surround it with either single or double quotes.

For more about specifying packages, see 'go help packages'.
For more about where packages and binaries are installed,
run 'go help gopath'.
For more about calling between Go and C/C++, run 'go help c'.

Note: Build adheres to certain conventions such as those described
by 'go help gopath'. Not all projects can follow these conventions,
however. Installations that have their own conventions or that use
a separate software build system may choose to use lower-level
invocations such as 'go tool compile' and 'go tool link' to avoid
some of the overheads and design decisions of the build tool.

See also: go install, go get, go clean.

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

[olej@dell ~]$ go help buildmode
The 'go build' and 'go install' commands take a -buildmode argument which
indicates which kind of object file is to be built. Currently supported values
are:

	-buildmode=archive
		Build the listed non-main packages into .a files. Packages named
		main are ignored.

	-buildmode=c-archive
		Build the listed main package, plus all packages it imports,
		into a C archive file. The only callable symbols will be those
		functions exported using a cgo //export comment. Requires
		exactly one main package to be listed.

	-buildmode=c-shared
		Build the listed main packages, plus all packages that they
		import, into C shared libraries. The only callable symbols will
		be those functions exported using a cgo //export comment.
		Non-main packages are ignored.

	-buildmode=default
		Listed main packages are built into executables and listed
		non-main packages are built into .a files (the default
		behavior).

	-buildmode=shared
		Combine all the listed non-main packages into a single shared
		library that will be used when building with the -linkshared
		option. Packages named main are ignored.

	-buildmode=exe
		Build the listed main packages and everything they import into
		executables. Packages not named main are ignored.


Всё на месте ;-)

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

Re: cборка приложений Go

Непрочитанное сообщение Olej » 11 май 2017, 22:59

Olej писал(а): Начинать нужно с версии Golang
Кроме того, под Linux вы можете собирать своё приложение GCC:

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

[olej@dell ~]$ gccgo --version
gccgo (GCC) 5.3.1 20160406 (Red Hat 5.3.1-6)
Copyright (C) 2015 Free Software Foundation, Inc.
Это свободно распространяемое программное обеспечение. Условия копирования
приведены в исходных текстах. Без гарантии каких-либо качеств, включая 
коммерческую ценность и применимость для каких-либо целей.
Со всеми привычными опциями компилятора GCC.

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

Re: cборка приложений Go

Непрочитанное сообщение Olej » 11 май 2017, 23:21

perseus писал(а):но на практике мне его реализовать не удаётся
Быстрый способ разрешить любую непонятную программную проблему - не объяснять на пальцах, а привести программный код, который вызывает ошибки.
А если этот код (проект) большой, то составить прототип, моделирующий проблему. Это, казалось бы, лишняя работа (писать код прототипа), но опыт показывает, что это сокращает затрачиваемое время в разы.

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

Re: cборка приложений Go

Непрочитанное сообщение Olej » 11 май 2017, 23:38

perseus писал(а): Как собрать статически слинкованную (staticaly linked) программу на GO, использующую библиотеки Tcl/Tk ? Чтобы команда Unix "ldd" при проверке исполняемого файла программы не выдавала никаких ссылок на динамические библиотеки,
Мне не совсем понятно намерение (цель) так сделать для работы в системе (UNIX-like), где используются разделяемые библиотеки поддержки сторонних языков программирования.
Так любят делать в Windows, но это дурной путь.
В чём смысл? (т.е. он может и есть ... но не так очевидно :oops: ).

Аватара пользователя
perseus
Писатель
Сообщения: 99
Зарегистрирован: 11 май 2017, 18:01
Откуда: Щёлково, Московская обл.
Контактная информация:

Re: cборка приложений Go

Непрочитанное сообщение perseus » 12 май 2017, 10:18

Касательно намерений (цели) сделать статическую сборку, мне нужно это по работе,
нужна автономная программа которая будет выполняться на удаленном оборудовании с ограниченным доступом, куда нет возможности грузить разделяемые библиотеки поддержки сторонних языков программирования.

Касательно версии у меня выдаёт go version xgcc (Ubuntu 4.9.3-0ubuntu4) 4.9.3.linux/386

Аватара пользователя
perseus
Писатель
Сообщения: 99
Зарегистрирован: 11 май 2017, 18:01
Откуда: Щёлково, Московская обл.
Контактная информация:

Re: cборка приложений Go

Непрочитанное сообщение perseus » 12 май 2017, 10:24

В моей версии go при запросе go help build в списке флагов отсутствует флаг -buildmode,
видимо нужно попробовать с другой версией go поэксперементировать.
Спасибо за подсказку, о результатах эксперимента отпишусь сюда.

Аватара пользователя
perseus
Писатель
Сообщения: 99
Зарегистрирован: 11 май 2017, 18:01
Откуда: Щёлково, Московская обл.
Контактная информация:

Re: cборка приложений Go

Непрочитанное сообщение perseus » 12 май 2017, 10:55

Вот результаты эксперемента с другой версией go: :shock:

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

maksim@maksim-MS-7519 /usr/lib/python3.4 $ go version
go version go1.7.1 linux/386
maksim@maksim-MS-7519 /usr/lib/python3.4 $ go help install
usage: go install [build flags] [packages]

Install compiles and installs the packages named by the import paths,
along with their dependencies.

For more about the build flags, see 'go help build'.
For more about specifying packages, see 'go help packages'.

See also: go build, go get, go clean.

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

maksim@maksim-MS-7519 /usr/lib/python3.4 $ go help build
usage: go build [-o output] [-i] [build flags] [packages]

Build compiles the packages named by the import paths,
along with their dependencies, but it does not install the results.

If the arguments to build are a list of .go files, build treats
them as a list of source files specifying a single package.

When compiling a single main package, build writes
the resulting executable to an output file named after
the first source file ('go build ed.go rx.go' writes 'ed' or 'ed.exe')
or the source code directory ('go build unix/sam' writes 'sam' or 'sam.exe').
The '.exe' suffix is added when writing a Windows executable.

When compiling multiple packages or a single non-main package,
build compiles the packages but discards the resulting object,
serving only as a check that the packages can be built.

When compiling packages, build ignores files that end in '_test.go'.

The -o flag, only allowed when compiling a single package,
forces build to write the resulting executable or object
to the named output file, instead of the default behavior described
in the last two paragraphs.

The -i flag installs the packages that are dependencies of the target.

The build flags are shared by the build, clean, get, install, list, run,
and test commands:

	-a
		force rebuilding of packages that are already up-to-date.
	-n
		print the commands but do not run them.
	-p n
		the number of programs, such as build commands or
		test binaries, that can be run in parallel.
		The default is the number of CPUs available.
	-race
		enable data race detection.
		Supported only on linux/amd64, freebsd/amd64, darwin/amd64 and windows/amd64.
	-msan
		enable interoperation with memory sanitizer.
		Supported only on linux/amd64,
		and only with Clang/LLVM as the host C compiler.
	-v
		print the names of packages as they are compiled.
	-work
		print the name of the temporary work directory and
		do not delete it when exiting.
	-x
		print the commands.

	-asmflags 'flag list'
		arguments to pass on each go tool asm invocation.
	-buildmode mode
		build mode to use. See 'go help buildmode' for more.
	-compiler name
		name of compiler to use, as in runtime.Compiler (gccgo or gc).
	-gccgoflags 'arg list'
		arguments to pass on each gccgo compiler/linker invocation.
	-gcflags 'arg list'
		arguments to pass on each go tool compile invocation.
	-installsuffix suffix
		a suffix to use in the name of the package installation directory,
		in order to keep output separate from default builds.
		If using the -race flag, the install suffix is automatically set to race
		or, if set explicitly, has _race appended to it.  Likewise for the -msan
		flag.  Using a -buildmode option that requires non-default compile flags
		has a similar effect.
	-ldflags 'flag list'
		arguments to pass on each go tool link invocation.
	-linkshared
		link against shared libraries previously created with
		-buildmode=shared.
	-pkgdir dir
		install and load all packages from dir instead of the usual locations.
		For example, when building with a non-standard configuration,
		use -pkgdir to keep generated packages in a separate location.
	-tags 'tag list'
		a list of build tags to consider satisfied during the build.
		For more information about build tags, see the description of
		build constraints in the documentation for the go/build package.
	-toolexec 'cmd args'
		a program to use to invoke toolchain programs like vet and asm.
		For example, instead of running asm, the go command will run
		'cmd args /path/to/asm <arguments for asm>'.

The list flags accept a space-separated list of strings. To embed spaces
in an element in the list, surround it with either single or double quotes.

For more about specifying packages, see 'go help packages'.
For more about where packages and binaries are installed,
run 'go help gopath'.
For more about calling between Go and C/C++, run 'go help c'.

Note: Build adheres to certain conventions such as those described
by 'go help gopath'. Not all projects can follow these conventions,
however. Installations that have their own conventions or that use
a separate software build system may choose to use lower-level
invocations such as 'go tool compile' and 'go tool link' to avoid
some of the overheads and design decisions of the build tool.

See also: go install, go get, go clean.

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

maksim@maksim-MS-7519 /usr/lib/python3.4 $ cd ..
maksim@maksim-MS-7519 /usr/lib $ cd home/maksim
bash: cd: home/maksim: No such file or directory
maksim@maksim-MS-7519 /usr/lib $ cd /home/maksim
maksim@maksim-MS-7519 ~ $ pwd
/home/maksim
maksim@maksim-MS-7519 ~ $ cd Progy/Go
maksim@maksim-MS-7519 ~/Progy/Go $ cd src
maksim@maksim-MS-7519 ~/Progy/Go/src $ pwd
/home/maksim/Progy/Go/src
maksim@maksim-MS-7519 ~/Progy/Go/src $ go install -buildmode=shared -linkshared std
go install runtime/internal/sys: mkdir /usr/local/go/pkg/linux_386_dynlink: permission denied
maksim@maksim-MS-7519 ~/Progy/Go/src $ su
Password: 
maksim-MS-7519 src # go install -buildmode=shared -linkshared std
The program 'go' is currently not installed. You can install it by typing:
apt-get install gccgo-go
maksim-MS-7519 src # 
Как видно из приведеммой распечатки команд, система требует установить и использовать для выполнения команды
go install -buildmode=shared -linkshared std
компилятор gccgo-go, НО в нем не определён флаг -buildmode как я уже писал выше :lol:
Замкнутый круг получается :oops:
Надо подумать :-?

Аватара пользователя
perseus
Писатель
Сообщения: 99
Зарегистрирован: 11 май 2017, 18:01
Откуда: Щёлково, Московская обл.
Контактная информация:

Re: cборка приложений Go

Непрочитанное сообщение perseus » 12 май 2017, 11:37

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

maksim-MS-7519 maksim # go version
go version xgcc (Ubuntu 4.9.3-0ubuntu4) 4.9.3 linux/386
maksim-MS-7519 maksim # pwd
/home/maksim
maksim-MS-7519 maksim # cd Progy/Go/src
maksim-MS-7519 src # go install -buildmode=shared -linkshared std
flag provided but not defined: -buildmode
usage: install [build flags] [packages]

Install compiles and installs the packages named by the import paths,
along with their dependencies.

For more about the build flags, see 'go help build'.
For more about specifying packages, see 'go help packages'.

See also: go build, go get, go clean.
Как видите gcc-go говорит, что у него не определён флаг -buildmode

Ответить

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

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

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