Reputation: 364
Macros may create functions in the global scope. For example:
(defmacro test-macro (&body functions)
`(progn ,@(loop for function in functions
collect `(defun ,function ()
*some-interesting-thing*))))
Another example (albeit with methods) would be the automatically generated accessors for a CLOS class.
The functions are not defined at macro expansion time, but rather when the generated code is compiled/interpreted. This can cause some difficulty. If these functions are being expected, a warning will be thrown. What is the idiomatic way to define these functions before they are correctly defined? One potential solution might be the following:
(defmacro test-macro (&body functions)
(macrolet ((empty-function (name)
`(defun ,name ())))
(dolist (function functions)
(empty-function function)))
`(progn ,@(loop for function in functions
collect `(defun ,function ()
*some-interesting-thing*))))
Note that the intermediate function is defined during macro expansion time.
Upvotes: 3
Views: 189
Reputation: 139411
If you need to define a function at compile time on the toplevel, then use:
(eval-when (:compile-toplevel)
(defun foo ...))
Note that you can define a macro which generates such code. Such a form can be part of a PROGN
.
Upvotes: 4