# 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:** 3

<div class="post-metadata">

**Author:** ![giordano](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/giordano/32/2166_2.png) [@giordano](https://discourse.julialang.org/u/giordano)\
**Post date:** [May 31, 2025, 10:52pm UTC](https://discourse.julialang.org/t/calling-c-code-with-automatic-differentiation-in-julia/129503/3 "2025-05-31T22:52:02Z")

</div>

My naive attempt

```julia-repl
julia> using Enzyme

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

julia> run(pipeline(`clang -x c - -fPIC -fembed-bitcode -shared -o libsquare.dylib`; stdin=IOBuffer(file)))
Process(`clang -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> first(first(autodiff(Reverse, csquare, Active, Active(3.14))))
ERROR:
No reverse pass found for ejlstr$square$./libsquare.dylib
 at context: %3 = call double @"ejlstr$square$./libsquare.dylib"(double %0) #5, !dbg !14

Stacktrace:
 [1] csquare
   @ ./REPL[16]:1

```

failed, so yeah, I hope they can provide a working example 🙂

_ **Edit** _: I found this thread [Is it possible to use autodiff on an external program? - #2 by wsmoses](https://discourse.julialang.org/t/is-it-possible-to-use-autodiff-on-an-external-program/108475/2) which suggests the same strategy, but without a working example.

_ **Edit 2** _: I managed not to get an error with

```julia-repl
julia> using Enzyme, Libdl

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

julia> run(pipeline(`clang -x c - -fPIC -fembed-bitcode -shared -o libsquare.dylib`; stdin=IOBuffer(file)))
Process(`clang -x c - -fPIC -fembed-bitcode -shared -o libsquare.dylib`, ProcessExited(0))

julia> fptr = dlsym(dlopen("./libsquare.dylib"), :square)
Ptr{Nothing} @0x0000000104833f9c

julia> csquare(x::Cdouble) = ccall(fptr, Cdouble, (Cdouble,), x)
csquare (generic function with 1 method)

julia> first(first(autodiff(Reverse, csquare, Active, Active(3.14))))
0.0

```

but the result is still wrong, so I’m clearly still missing something.

---

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