Zihemu Zihemu - 2 months ago 7
C Question

How to mix C++ and C correctly

I am having some problems with this: I need to write a C wrapper for a C++ library. Say I have 3 files:


  • wrapper.h

    typedef struct Foo Foo;
    Foo* create_foo();

  • wrapper.cpp

    extern "C" {
    #include "wrapper.h"
    }
    #include "foo.h"

    Foo* create_foo() {
    return new Foo;
    }

  • foo.h

    class Foo {
    public:
    Foo();
    };



This compiles fine:

clang++ -std=c++14 wrapper.cpp foo.h wrapper.h -shared -fPIC


clang++ -shared -o libbindings.so a.out


but when compiling the program that uses the C wrapper (it is compiler and linked by the programming language that uses the wrapper - Crystal), I get an undefined reference to create_foo() and a linker error
collect2: error: ld returned 1 exit status
. How can I debug this (and what am I doing wrong)?

Answer

Here is a working example:

wrapper.h (C & C++ aware)

#ifndef WRAPPER_H_
#define WRAPPER_H_

#ifdef __cplusplus
extern "C" {
#endif

typedef struct CPPClass CPPClass;

CPPClass* CPPClass_new();
void CPPClass_do_something(CPPClass* cppclass);
int CPPClass_get_state(CPPClass* cppclass);
void CPPClass_delete(CPPClass* cppclass);

#ifdef __cplusplus
}
#endif
#endif /* WRAPPER_H_ */

wrapper.cpp (C++ only)

#include "wrapper.h"

class CPPClass
{
    int state;
public:
    CPPClass(): state(0) {}
    void do_something() { ++state; }
    int get_state() const { return state; }
};

extern "C" CPPClass* CPPClass_new()
{
    return new CPPClass;
}

extern "C" void CPPClass_do_something(CPPClass* cppclass)
{
    cppclass->do_something();
}

extern "C" int CPPClass_get_state(CPPClass* cppclass)
{
    return cppclass->get_state();
}

extern "C" void CPPClass_delete(CPPClass* cppclass)
{
    delete cppclass;
}

use-wrapper.c (C only)

#include <stdio.h>
#include "wrapper.h"

int main(void)
{
    CPPClass* cppclass = CPPClass_new();

    if(!cppclass)
    {
        printf("ERROR: failed to create CPPClass:\n");
        return 1;
    }

    printf("state: %d\n", CPPClass_get_state(cppclass));
    CPPClass_do_something(cppclass);
    printf("state: %d\n", CPPClass_get_state(cppclass));

    CPPClass_delete(cppclass);
}

Compile CPP

g++ -std=c++11 -shared -fPIC -c -o libwrapper.so wrapper.cpp

Compile C

gcc -o use-wrapper use-wrapper.c -L. -lwrapper -lstdc++

Output:

$ ./use-wrapper 
state: 0
state: 1

Hope that helps.