As a result of hiding the implementation of our machine away in the emulate.c file, the main program main.c is very simple. This is how it should be. A programmer using our library shouldn't have to be concerned with how our library works. They just need to know what it does, just like the standard C libraries. Usually this explanation of what a library does, and what data structures and functions are available to a programmer is included either as comments in the header file of the library itself, or as a carefully written help file which is distributed with the library.
The first thing the main program needs to do is to make an instance of a machine. This is done by having a variable which points to a machine. We call this pointer mymachine, thus:
machine * mymachine;
The next line of our program simply waits for a keypress by using the getchar() function.
Next we call the initialise function of our library. This allows-na the library to initialise any internal data structures it might use and get ready for operation. In this case, the initialise function also creates an instance of a machine in memory, sets all the initial values stored in the registers, and so on, and returns a pointer to this machine. We assign this to our pointer mymachine to keep track of it.
Note that we only store the pointer to the machine itself in order to pass to the function emulate later on in the main program. Since the main program doesn't particularly care how the machine is emulated, or need access to its internals, it is not strictly necessary to have this pointer passed back to the main program. The library could just internally keep track itself, of any machine that it creates.
The next series of lines should now be self explanatory. We fill the memory locations of our machine (starting at location 0) with the code that the machine is to execute. Note that we refer to the instructions by their opcode mnemonic, by virtue of the enum that we defined, rather than by numbers that stand for the opcodes. When the program is compiled, the compiler replaces all these mnemonics with the respective integers that should be used.
Now we simply call the emulate function. It has two parameters. The first is the location in emulated memory that the machine should start execution from. Since we loaded our program into memory location 0 and following, we supply 0 for this parameter. The second parameter is just a pointer to a machine that has been initialised.
Finally, our program waits for another keypress from the user, by running getchar(), and then exits.
As you see, all the details of how the machine actually carries out its functions, is hidden away in the emulate.c file, which we are yet to discuss in detail.