Ch.5 Setting up SML# programming environment

§ 5.6. Let's try SML# compile mode

The main function of SML# compiler is to compile a file and to create an executable program, just like gcc.

As a simple example, let us write the previous user input # "Hello world"; into a file hello1.sml:

"Hello world";

The trailing semicolon does not have any effect in a file. This file can be compiled as follows.

$ smlsharp hello1.sml
$ file a.out
a.out: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.18, not stripped

When only a file name is given, SML# compiles the file, link it and creates an executable file, whose default name is a.out. As shown by the Linux file command, it is an ordinary executable file. The output file name can be specified by a -o switch.

$ smlsharp -o hello1 hello1.sml
$ ls hello1*
hello1 hellp1.sml

The generated executable file can then be executed.

$ ./hello1

Nothing is printed by this program. This is what you expect. SML# compiles the source code itsel; it does not attach code to print the result value and its type. If you want to see something printed, you need to write code to print it explicitly. Now let's create a file hello2.sml to print this message. The contents can be the following.

print "hello world!\n"

This file contains a function print which is not defined in this file. Our intention is that print denotes the function print : string -> unit in Standard ML Basis Library. However, since name print can be freely re-defined, for SML# compiler, it does not necessarily mean the library function. In order to compile hello2.sml, you need to notify the compiler where the name print is defined. For this purpose, an interface file must be created.

When compiling hello2.sml, SML# searches for its interface file by its default name hello2.smi. So to compile hello2.sml, you need to create file hello2.smi. Its contents can be the following.

_require "basis.smi"

This declares that hello2.sml uses names that are defined in the interface file "basis.smi", which is the system supplied file containing the declarations of all the names defined in the Standard ML Basis Library.

With this preparation, hello2.sml is compiled as follows.

$ smlsharp hello.sml -o hello
$ ./hello
hello word!