Can I use shared library created in C++ in a C program?

前端 未结 3 1688
情话喂你
情话喂你 2020-12-04 08:26

I am creating programs using C. However, I require to use a lot of libraries that have API\'s only for C++. So, is it possible that I can create a shared object in C++ and t

3条回答
  •  甜味超标
    2020-12-04 09:31

    This is entirely possible. Here is how, quickly: 1.) You have a header.h with a C API that doesn't include any Cplusiness.

    #ifndef MIXEDCCPP_H
    #define MIXEDCCPP_H
    
    #ifdef __cplusplus
    extern "C" {
    #endif
    #include  // Any C-compatible headers will go here.
    
    // C API goes here.  C Functions can't contain any CPPiness.
    void myclass_setName( void *pClassObj, const char *pName, int nameLen );
    
    #ifdef __cplusplus
    }
    #endif
    
    #ifdef __cplusplus
    
    // Stuff that is only compatible with CPP goes here
    // __cplusplus section won't get processed while compiling C files.
    
    #include  // CPP headers.
    
    
    class MyClass {
       // Classes etc.
    };
    #endif // #ifdef __cplusplus
    
    #endif // MIXEDCCPP_H
    

    Then in the .cpp, you simply create some C-API functions that can even include CPP right in them:

    #include "mixedccpp.h"
    
    extern "C" {
    // C API goes here.  C Functions can't contain any CPPiness in their prototypes.
    void myclass_setName( void *pClassObj, const char *pName, int nameLen )
    {
        // But CPP knowledge can go inside the function - no problem, since this is a CPP file.
        MyClass *pMyClass = static_cast(pClassObj);
        pMyClass->setName( pName, nameLen );
    }
    
    } // #extern "C"
    
    
    // CPP Stuff goes here... or vice-versa.
    

    In your case, you don't actually need any CPP code declared in your header since you are calling external libraries. But you need to create C-compatible functions in your CPP file which can call out to CPP libraries. Use extern "C" for those functions that need to be called from C files, and then use C-structs instead of classes and, if classes are needed, use void * to point to them and then cast them back to their class from the C function any time you need to access them. A standard makefile should be able to compile this just fine, assuming it compiles .cpp files as .cpp and understands extern "C" {}

提交回复
热议问题