使用 go 动态创建编译后的二进制文件
Dynamically create compiled binary with go
首先,对于一个糟糕的标题,我深表歉意 - 我想我遇到的很多困难都与不知道我想要实现的目标的正确术语有关。
在 Go 中,我希望有一个程序可以在 运行 时动态创建辅助二进制文件。用一个基本的 hello world 示例来说明 - 在伪代码中,因为我不知道如何实现它。
generator.go
-> Read in statement from statement.txt (i.e. "Hello World")
-> Insert this statement into the following program...
package main
import (
"fmt"
)
func main(){
fmt.Println([dynamic statement inserted here])
}
-> compile this code into subprogram
每当执行 go run generator.go
时,都会创建一个 subprogram
二进制文件。 运行 这将输出 Hello World
。将 statement.txt 更改为其他内容并再次执行 go run generator.go
将再次创建 subprogram
,当 运行 将执行新语句时。
总结
使用 Go,我如何创建一个可以动态创建已编译 child 程序作为输出的程序。
谢谢。
所以你有 2 个子任务,它们一起做你想做的事:
- 执行文本替换以获取最终源代码。
- 将最终源代码编译成可执行二进制文件。
1。文本替换
第一个可以使用 text/template
包轻松完成。您可以将源模板作为单独的单独文件,或嵌入到主 Go 源中(例如 const
s)。
您可以构建/解析源代码模板并获得 Template
with e.g. template.ParseFiles()
or using template.New().Parse()
. Once you have your template, assemble (e.g. load from file) the values you want to include in the source template and execute it e.g. with Template.Execute()
。您现在拥有最终来源。
text/template
包为您提供了一个强大的模板引擎,其功能远不止文本替换。
注意: 在 go
的子包中,标准库中还实现了一个 Go 解析器供您使用,但使用 text/template
包要简单得多,看起来就足够了,非常适合你的情况。
2。编译
要将最终的源代码编译成可执行的二进制文件,需要编译器的帮助。您可以使用 os/exec
package to invoke the compiler which will produce the binary. See the exec.Command()
function to acquire a Cmd
, and Cmd.Run()
and Cmd.Start()
来执行它。
首先,对于一个糟糕的标题,我深表歉意 - 我想我遇到的很多困难都与不知道我想要实现的目标的正确术语有关。
在 Go 中,我希望有一个程序可以在 运行 时动态创建辅助二进制文件。用一个基本的 hello world 示例来说明 - 在伪代码中,因为我不知道如何实现它。
generator.go
-> Read in statement from statement.txt (i.e. "Hello World")
-> Insert this statement into the following program...
package main
import (
"fmt"
)
func main(){
fmt.Println([dynamic statement inserted here])
}
-> compile this code into subprogram
每当执行 go run generator.go
时,都会创建一个 subprogram
二进制文件。 运行 这将输出 Hello World
。将 statement.txt 更改为其他内容并再次执行 go run generator.go
将再次创建 subprogram
,当 运行 将执行新语句时。
总结
使用 Go,我如何创建一个可以动态创建已编译 child 程序作为输出的程序。
谢谢。
所以你有 2 个子任务,它们一起做你想做的事:
- 执行文本替换以获取最终源代码。
- 将最终源代码编译成可执行二进制文件。
1。文本替换
第一个可以使用 text/template
包轻松完成。您可以将源模板作为单独的单独文件,或嵌入到主 Go 源中(例如 const
s)。
您可以构建/解析源代码模板并获得 Template
with e.g. template.ParseFiles()
or using template.New().Parse()
. Once you have your template, assemble (e.g. load from file) the values you want to include in the source template and execute it e.g. with Template.Execute()
。您现在拥有最终来源。
text/template
包为您提供了一个强大的模板引擎,其功能远不止文本替换。
注意: 在 go
的子包中,标准库中还实现了一个 Go 解析器供您使用,但使用 text/template
包要简单得多,看起来就足够了,非常适合你的情况。
2。编译
要将最终的源代码编译成可执行的二进制文件,需要编译器的帮助。您可以使用 os/exec
package to invoke the compiler which will produce the binary. See the exec.Command()
function to acquire a Cmd
, and Cmd.Run()
and Cmd.Start()
来执行它。