Configuring the CLASSPATH environment

Starting with the nbody simulation project, we’ll be writing more sophisticated Kotlin programs—ones that call library functions written by other people. The library we’ll be using is called stdlib and was written by Robert Sedgewick at Princeton University.

To compile and run Kotlin programs that call stdlib functions, you have to provide command line flags when invoking the kotlinc and kotlin commands, like this

$ kotlinc -cp PATHS_TO_ALL_NECESSARY_CLASS_FILES source.kt

and

$ kotlin -cp PATHS_TO_ALL_NECESSARY_CLASS_FILES SourceKt

Repeatedly typing in these long commands can get tiring. I will tell you how to shorten them a bit.

OS X users

If you are running OS X, follow these steps:

  1. Download stdlib.jar. By default, your browser should put it in your ~/Downloads directory.
  2. Fire up your terminal and type

    $ mkdir ~/JavaLib; mv ~/Downloads/stdlib.jar ~/JavaLib
  3. If you already have a ~/.bash_profile file, open it with your text editor and add these lines to it. Otherwise, just create one and put these lines in:

    export CLASSPATH=".:/Users/YOUR_LOGIN_NAME/JavaLib/stdlib.jar"
    alias kotlinc="kotlinc -cp $CLASSPATH"
    alias kotlin="kotlin -cp $CLASSPATH"
    However, make sure to replace YOUR_LOGIN_NAME with your real login name.
  4. Quit your terminal app. Reopen your terminal app and cd to the directory where you’re keeping your Kotlin programs. For example, you will probably type something like

    $ cd ~/mcs178/nbody-project

Now you can compile your Kotlin program file.kt by typing

$ kotlinc file.kt

and then run the resulting class file by typing

$ kotlin FileKt

just like you have been doing all along. Well, unless your program needs some command line arguments of its own, or you want to redirect the standard input to some pre-prepared input file. Then you would have to type in those things as well.

Windows 10 users with WSL installed

If you are running WSL, do these:

  1. Follow the same steps as for OS X with two differences. The first difference is that the line

    export CLASSPATH=".:/Users/YOUR_LOGIN_NAME/JavaLib/stdlib.jar"

    to be added to your ~/.bash_profile file for OS X users should be changed to

    export CLASSPATH=".:/home/YOUR_LOGIN_NAME/JavaLib/stdlib.jar"

    for WSL users. The second difference is that you should also add the lines

    export DISPLAY=:0
    source ~/.bashrc

    to the end of your ~/.bash_profile file.

  2. Go here to download the X-server VcXsrc and install it. Before running any kotlin program that displays graphics, you must run the X-server first.