# Using a C++ library from Racket

**URL:** <https://racket.discourse.group/t/using-a-c-library-from-racket/2581>\
**Category:** Questions & Answers\
**Created:** [December 9, 2023, 2:22am UTC](https://racket.discourse.group/t/using-a-c-library-from-racket/2581 "2023-12-09T02:22:50Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![hendrikboom3](https://yyz2.discourse-cdn.com/free1/user_avatar/racket.discourse.group/hendrikboom3/32/2748_2.png) [@hendrikboom3](https://racket.discourse.group/u/hendrikboom3)\
**Post date:** [December 9, 2023, 2:22am UTC](https://racket.discourse.group/t/using-a-c-library-from-racket/2581/1 "2023-12-09T02:22:50Z")

</div>

I would like to use an existing C++ library from a Racket program. The library is sufficiently complicated that the authors figured they needed C++

How should I go about that?

Presumably using the ffi.  
Is there existing documentation about using ffi with C instead of C++?

Or do I need to define my own set of C-interfaced functions (using something like extern "C" in new C++ code that I write) and call them from Racket's ffi?

Presumably there will be issues with system initialization. Doesn't C++ like to own the main() function?

Presumably there will be issues with C++'s storage allocation. It has its own ideas about constructors, destructors, pointer copying, etc. How to set things up so that C++ will use these properly and not get interference from the garbage collector?

-- hendrik

---

<div class="post-metadata">

**Author:** ![nikhilm](https://avatars.discourse-cdn.com/v4/letter/n/f08c70/32.png) [@nikhilm](https://racket.discourse.group/u/nikhilm)\
**Post date:** [December 10, 2023, 12:09am UTC](https://racket.discourse.group/t/using-a-c-library-from-racket/2581/2 "2023-12-10T00:09:20Z")

</div>

Without knowing more details, yes, you will need to define a C API for the C++ library.

Native C++ libraries do name mangling. The C API will expose a non-mangled version. It will also take care of fitting the C++ object model into something that can work with raw pointers, plain-old-data and manage memory, such that Racket (or another higher language) can safely use the FFI constructs with the garbage collector.

Most C++ libraries do not need to own the main() function. If they need one time initialization, they will usually provide a function for that. You will have to make sure your Racket bindings also call that function before doing other operations.
