How to permanently save a macro in LISP (sbcl)

Viewed 48

Lets say i define a macro

(defmacro foo(x)
    (print x))

Now i want to be able to always load this macro in all my lisp files in future where should i save this macro?

2 Answers

Every CL implementation has an init file it calls on start. For SBCL that is ~/.sbclrc. Usually also quicklisp has some setup code in there if you installed quicklisp.

So you could add a line:

(load #P"path/to/your/macro/file.lisp")

And it'll get loaded each time you start SBCL.

You want to have a library.

A library can contain any number of definitions, not only macros.

The de facto standard way to define systems (which is a more general term for libraries, frameworks, and applications — units of software) is to use ASDF.

Let's say that you put your macro into a lisp file:

;;;; my-util.lisp

(in-package cl-user)

(defpackage my-util
  (:use cl))

(in-package my-util)

(defmacro foo (x)
  `(whatever ,x etc))

Then you put that under a directory that is known to ASDF. One useful directory for that is ~/common-lisp/, so let's use ~/common-lisp/my-util/. In the same directory, put the system definition file:

;;;; my-util.asd

(in-package asdf-user)

(defsystem "my-util"
  :components ((:file "my-util")))

Now you can load this utility into any lisp interaction, e. g. on the repl:

CL-USER> (asdf:load-system "my-util")

Or in a different system:

;;;; my-application.asd

(in-package asdf-user)

(defsystem "my-application"
  :depends-on ("my-util")
  ...)

In the case of utility libraries, you often want to use their package so that you don't need to package-qualify the symbols.

If you want things that only work on your computer (like shortcuts for your REPL use or one-off scripts), you can sometimes get away with adding things to your implementation's init file.

Related