'How to permanently save a macro in LISP (sbcl)

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?



Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Svante