About Generating Executable Files in the Go Language

Asked 2 years ago, Updated 2 years ago, 91 views

Is it possible to create a program in the Go language that receives a string from a standard input and generates an executable file that outputs the string to the standard output?
Also, what are the possible ways?

I want to create a simple compiler in Go language, but I don't know how to dynamically generate executables from programs.
Thank you for your cooperation.

6/24 8:48 I have corrected the points you pointed out in the comment.

go

2022-09-30 20:52

2 Answers

I'd like to create a simple compiler in Go language, but I'm not sure how to dynamically generate executable files from the program.

Comment Quotation: I'm thinking of something that works native on Linux.

It is possible to create a compiler in the Go language.If you want to generate a executable that runs native on Linux directly, you must first print the ELF (Executable and Linkable Format) header, followed by the machine language code string for your architecture.

Comment Quote: Is the only way to output binary files in executable format in Go is to manually specify bytes one at a time and output them?

Yes, outputting bytes in executable format is a key feature of the compiler itself.

However, in the actual compiler toolchain, it is common to divide roles according to the processing phase, rather than taking charge of everything in a single program.

  • From source code to phrase analysis, syntax analysis, and semantic analysis are called front-end parts.The abstract syntax tree is the output of these processes.
  • Subsequent code optimization, per code generation, is called the backend.Each code generation unit requires a specific one for the target architecture.

If you're building your own backend, at least you need to know enough to program the assembler in the target CPU architecture.If you find it so difficult to make your own, we recommend utilizing your existing compiler infrastructure, such as Intermediate Expressions (IR) for LLVM.


2022-09-30 20:52

To put it literally, is it as follows?

UPDATE: 2015-06-25 1:04
I posted an example using os.Args[1:], but you pointed out that it was not standard input, so I corrected it.

Receive a string from the standard input in Go language and output it to the standard output

Reprinted from bufio-The Go Programming Language

package main

import(
    "Bufio".
    "fmt"
    "os"
)

funcmain(){
    scanner:=bufio.NewScanner(os.Stdin)
    for scanner.Scan(){
        fmt.Println(scanner.Text())//Println will add back the final'\n'
    }
    if err: =scanner.Err(); err!=nil{
        fmt.Fprintln(os.Stderr, "reading standard input:", err)
    }
}

Generate executables

$go build echo.go
$ echo Hello World| ./ echo
Hello World

$ ./echo
Hello World!//<- User input
Hello World!//<- Response


2022-09-30 20:52

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.