Calling C++ Code from C

If you’ve been doing this for any length of time, you may have noticed that nothing wants a C++ library. Apache, Lua, you name it, they all want a C library. Clearly nobody writes C++, right? Luckily, this is not true; you can make your C++ code look like C code, and nobody will be the wiser!

The Trick

The trick is that when you make your library, you must use extern "C" for the functions you are exposing. For instance, see this totally useful C++ function:

void test_function(void)
std::cout << "hello from c++!" << std::endl;

What kind of place would the world be if random C programmers couldn’t call this function? Luckily for the computer science community we’re here. Like Prometheus before us, we’ll steal this secret and bring it to the masses! The way to use this from C is to declare it in your header like so:

extern "C" void test_function(void);

You can also use this in blocks:

extern "C"

Meanwhile, in C…

Like all things in C, dynamically loading and using this code is tedious, but workable. First things first, we must ensure to #include <dlfcn.h>. After this is done, you can get to work. First, you should create a void pointer for your library, and however many function pointers for your functions:

void * lib;
void (*test_func)(void);

After that is done, you may open your library:

lib = dlopen("/path/to/", RTLD_LAZY);

Next, we retrieve our symbols from the library. This will populate your function pointer:

test_func = dlsym(lib, "test_function");

After that is done, we can call our function:


Now that we’ve revolutionized software development, we should be sure to close our library handle. Leaking resources being bad and all…:


A Pattern Forming

Now, let’s compile our program and bask in the glory of our library!

main.c:20: undefined reference to `dlopen'
main.c:22: undefined reference to `dlsym'
main.c:26: undefined reference to `dlclose'

Ugh… Seems familiar… No matter. It turns out that we have to link it in manually like we did with math.h, this time with -ldl.

Now that we have that settled, let’s try this again…

hello from c++!

Much better.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: