Generate function in macro

I’m trying to generate a function in a macro when it’s called, but I can’t seem to get this to work. The desired behavior is that the function Library.test_function/0 is created when the macro Library.create_function/0 is called during compile time. Here is my code:

library.ex

defmodule Library do
  defmacro create_function() do
    quote do
      def unquote(:"test_function")() do
        "this is test_function"
      end
    end
  end
end

project.ex

defmodule Project do
  require Library
  Library.create_function()
end

The application compiles correctly, but when I enter iex it is not possible to call Library.test_function/0 as it appears not to be defined. Why is this?

1 Like

Oh yeah, it might be because the Library module is already compiled when Library.create_function/0 is called so then no new functions can be injected. Is that it?

You are expanding your macro from Project, so the function will get injected there, not in Library.

2 Likes

Oh, so that’s how it works. Thanks!