# Use a macro inside a function's definition

**URL:** <https://discourse.julialang.org/t/use-a-macro-inside-a-functions-definition/86321>\
**Category:** New to Julia\
**Tags:** question, macros\
**Created:** [August 25, 2022, 12:13pm UTC](https://discourse.julialang.org/t/use-a-macro-inside-a-functions-definition/86321 "2022-08-25T12:13:54Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Jeroen](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jeroen/32/39091_2.png) [@Jeroen](https://discourse.julialang.org/u/Jeroen)\
**Post date:** [August 25, 2022, 12:13pm UTC](https://discourse.julialang.org/t/use-a-macro-inside-a-functions-definition/86321/1 "2022-08-25T12:13:55Z")

</div>

Hello,

I have a function called `f′` and I want to use a macro called `@diff` inside the function’s definition:

```julia
macro diff(expression)
    return :(2x)
end

f′(x) = @diff x^2

print(f′(10))

```

Yet once I run this code, this error message is shown:

```julia
ERROR: LoadError: UndefVarError: x not defined
Stacktrace:
 [1] f′(x::Int64)
   @ Main ~/Code/julia/script.jl:5
 [2] top-level scope
   @ ~/Code/julia/script.jl:7
in expression starting at /Users/jeroen/Code/julia/script.jl:7

```

And this is the code that the macro produces (using `@macroexpand @diff x^2`):

```julia
2 * Main.x

```

I think the problem is that Julia binds the variable `x` to the main scope, instead of the function scope.

How can I overcome this problem and use macros inside function definitions?

Thank you!

---

<div class="post-metadata">

**Author:** ![johnmyleswhite](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/johnmyleswhite/32/31_2.png) [@johnmyleswhite](https://discourse.julialang.org/u/johnmyleswhite)\
**Post date:** [August 25, 2022, 1:04pm UTC](https://discourse.julialang.org/t/use-a-macro-inside-a-functions-definition/86321/2 "2022-08-25T13:04:27Z")

</div>

The macro definition is missing an `esc` call to indicate that you want to make the macro unhygienic and potentially corrupt the caller’s namespace:

```julia
macro diff(expression)
   esc(:(2x))
end

```

With that, the rest of your code works.

---

<div class="post-metadata">

**Author:** ![enderw88](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/enderw88/32/48997_2.png) [@enderw88](https://discourse.julialang.org/u/enderw88)\
**Post date:** [May 12, 2023, 4:30pm UTC](https://discourse.julialang.org/t/use-a-macro-inside-a-functions-definition/86321/3 "2023-05-12T16:30:37Z")

</div>

@johnmyleswhite thank you, this was stumping me.
