1
defmodule BBB do
  IO.puts "BBB"
  defmacro hh do
    IO.puts "hh in BBB"
  end
end

defmodule AAA do
  IO.puts "AAA"
  require BBB
  BBB.hh
end

Why is the output:

BBB
hh in BBB
AAA

I'm really confused by the compiling process in Elixir.

1 Answer 1

6

I'm assuming you expected hh in BBB to be after AAA. The reason it's the reverse of that is because when AAA is compiled, the macro hh is first expanded. Since hh prints a value directly instead of returning a quoted fragment that prints, it's executed before any expressions in the AAA module are executed.

If you change hh to be a normal def instead of defmacro:

def hh do
  IO.puts "hh in BBB"
end

or you change defmacro hh to return quoted AST which prints the string:

defmacro hh do
  quote do
    IO.puts "hh in BBB"
  end
end

the output will be AAA first and then hh in BBB.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.