Learning notes of "write java virtual machine by yourself" (1) --- command line tool

In March of this year, I read this book, but I may not have enough knowledge reserve. I know a lot of things, so I can't read half of them. Now I feel that I have made great progress. I decided to pick up this book again and record the learning process.

The tools used in this book, the go language development environment, can be downloaded from the official website. After downloading, you need to configure the environment variables, that is, the workspace, where we put the code, and the tools for writing the code. I use the sublime Text3 recommended in the book, which can also be downloaded from the Internet, free of charge

The first chapter is mainly about command line parsing tools. If we have used the console to compile the code, we can compile the code by inputting instructions in the console. After generating the class file, we can continue to run it through commands.

So, the first step is to parse these commands

First, the structure of a command line

There are almost no notes on the book. I added notes according to my understanding and searching materials

package main 

import "flag"
import "fmt"
import "os"

type Cmd struct{
	helpFlag  bool
	versionFlag bool
	cpOption string
	class string
	args []string
func parseCmd() *Cmd{
	//Declare a structure pointer
    //I think it's the user guide
	//Register a bool type flag with the specified name, default value and usage information, and save the value of the flag to the address pointed to by & cmd.helpflag
	flag.BoolVar(&cmd.helpFlag,"help",false,"print help message")
	flag.BoolVar(&cmd.helpFlag,"?",false,"print help message")
	flag.BoolVar(&cmd.versionFlag,"version",false,"print version and exit")
	//Resolve the command to the corresponding registered variable

    if len(args)>0{
    //Pointer to return parsing result
    return cmd
func printUsage(){
	fmt.Print("Usage: %s [-options] class [args...]\n",os.Args[0])

The function to parse the command line has been written, followed by the main function

package main

import "fmt"

func main(){
	//Call the number of lines of the parsing command line to accept the parsing result
    if cmd.versionFlag{
    	fmt.Println("version 0.0.1")
    }else if cmd.helpFlag||cmd.class==""{

func startJVM(cmd *Cmd){
	fmt.Printf("classpath:%s class:%s args:%v\n",cmd.cpOption,cmd.class,cmd.args)

It's a success here

Let's compile and run it

Tags: sublime Go

Posted on Wed, 18 Dec 2019 14:15:20 -0800 by jacko_162