Writing a C++ wrapper for a C library

stripes picture stripes · May 3, 2010 · Viewed 10k times · Source

I have a legacy C library, written in an OO type form. Typical functions are like:

LIB *lib_new();
void lib_free(LIB *lib);
int lib_add_option(LIB *lib, int flags);
void lib_change_name(LIB *lib, char *name);

I'd like to use this library in my C++ program, so I'm thinking a C++ wrapper is required. The above would all seem to map to something like:

class LIB
{
    public:
         LIB();
         ~LIB();
         int add_option(int flags);
         void change_name(char *name);
...
};

I've never written a C++ wrapper round C before, and can't find much advice about it. Is this a good/typical/sensible approach to creating a C++/C wrapper?

Answer

anon picture anon · May 3, 2010

A C++ wrapper is not required - you can simply call the C functions from your C++ code. IMHO, it's best not to wrap C code - if you want to turn it into C++ code - fine, but do a complete re-write.

Practically, assuming your C functions are declared in a file called myfuncs.h then in your C++ code you will want to include them like this:

extern "C" {
   #include "myfuncs.h"
}

in order to give them C linkage when compiled with the C++ compiler.