# Calling C Code with Automatic Differentiation in Julia

**URL:** <https://discourse.julialang.org/t/calling-c-code-with-automatic-differentiation-in-julia/129503>\
**Category:** Numerics\
**Tags:** question, differentiation, c, autodiff\
**Created:** [May 31, 2025, 2:56pm UTC](https://discourse.julialang.org/t/calling-c-code-with-automatic-differentiation-in-julia/129503 "2025-05-31T14:56:13Z")\
**Posts on this page:** 1\
**Showing post:** 6

<div class="post-metadata">

**Author:** ![wsmoses](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/wsmoses/32/26497_2.png) [@wsmoses](https://discourse.julialang.org/u/wsmoses)\
**Post date:** [June 2, 2025, 12:20am UTC](https://discourse.julialang.org/t/calling-c-code-with-automatic-differentiation-in-julia/129503/6 "2025-06-02T00:20:37Z")

</div>

It appears julia changed its FFI runtime calls since last someone tried, but in any case on latest Enzyme.jl (0.13.48) and Julia 1.10 or 1.11, this should work:

```julia
(base) wmoses@hydra:~/git/Enzyme.jl$ julia +1.10 --project 
               _
   _ _ _(_)_ | Documentation: https://docs.julialang.org
  (_) | (_) (_) |
   _ _ _| |_ __ _ | Type "?" for help, "]?" for Pkg help.
  | | | | | | |/ _` | |
  | | |_| | | | (_| | | Version 1.10.9 (2025-03-10)
 _/ |\ __'_|_|_|\__'_| | Official https://julialang.org/ release
|__/ |

julia> using Enzyme
       # Enzyme.Compiler.DebugLTO[] = true

julia> file = """
              double square(double x) {
                  return x * x;
              }
              """;

julia> run(pipeline(`/home/wmoses/llvms/llvm15/buildD/bin/clang -Xclang -no-opaque-pointers -x c - -fPIC -fembed-bitcode -shared -o libsquare.dylib`; stdin=IOBuffer(file)))
Process(`/home/wmoses/llvms/llvm15/buildD/bin/clang -Xclang -no-opaque-pointers -x c - -fPIC -fembed-bitcode -shared -o libsquare.dylib`, ProcessExited(0))

julia> csquare(x::Cdouble) = @ccall "./libsquare.dylib".square(x::Cdouble)::Cdouble
csquare (generic function with 1 method)

julia> @show first(first(autodiff(Reverse, csquare, Active, Active(3.14))))
first(first(autodiff(Reverse, csquare, Active, Active(3.14)))) = 6.28
6.28

```

Note that you need the version of clang to be less than or equal to the version of LLVM used by Julia (e.g. 15 for Julia 1.10 or 16 for 1.11).

---

_[View the full topic](https://discourse.julialang.org/t/calling-c-code-with-automatic-differentiation-in-julia/129503)._
