Loading a file in common lisp

Charles Langlois picture Charles Langlois · Jun 1, 2015 · Viewed 7.2k times · Source

I've been learning/playing around with common lisp for some time(few months), and I still have some difficulty understanding how to import code from other files. I'm using emacs/slime and SBCL, and from what I've read, I need to use the "load" function to load the code from another file. I also define packages and put the name of the packages I want to import in the ":use" clause. However, slime keeps complaining the file(s) I'm trying to load does not exist(when it clearly does). What am I doing wrong? Example:

(load "file.lisp")
(defpackage :package
  (:use :cl :file))
...

Thanks.

Answer

Mark Karpov picture Mark Karpov · Jun 1, 2015

You don't necessarily need to define a package to use code from other files. Simply put, package is a means of abstraction and separation of your code from other code. It's not designed to keep information about which file depends on which.

To organize your files (there are usually many files that are all reside in one package), you need a thing called system, at least in ASDF terminology.

Before we speak about ASDF, I want to note that your load method can be used too, although it's rather suitable for toys, simple sketches, or for use at REPL. You can manually load things — it should work. If it doesn't work for you, first try to specify full path to your file. Next thing you can do if specifying full path helps, is make sure your CL implementation knows where to search for the file if file name is relative. But this is a different topic, and not very interesting one.

Normally, ASDF is used nowadays to organize all sorts of projects, from small to big. You should study the documentation to understand how to use ASDF, but even simple example can tell your a lot:

(asdf:defsystem "hello-lisp"
  :description "hello-lisp: a sample Lisp system."
  :version "0.0.1"
  :author "Joe User <[email protected]>"
  :licence "Public Domain"
  :components ((:file "packages")
               (:file "macros" :depends-on ("packages"))
               (:file "hello"  :depends-on ("macros"))))

Here you can have some meta-data about your project, and the most important thing — information about structure of the project. I think it's pretty self-explanatory.

How to get ASDF? Good news for you, since you mentioned that you're using SBCL, it's already installed.

As a rule, every programming language has some sort of ecosystem, that allows you to define structure of your programs (dependencies between files and external dependencies — libraries, etc.). It's an important thing to learn. In Common Lisp world such an ecosystem is formed by combination of ASDF and Quicklisp — library manager that allows you to automatically install dependencies of your project, for example. Plan your journey carefully and take a look at these tools!