Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing C++ library in C code
    text
    copied!<p>I have a C++ library that provides various classes for managing data. I have the source code for the library.</p> <p>I want to extend the C++ API to support C function calls so that the library can be used with C code and C++ code at the same time.</p> <p>I'm using GNU tool chain (gcc, glibc, etc), so language and architecture support are not an issue.</p> <p>Are there any reasons why this is <strong>technically</strong> not possible?</p> <p>Are there any <strong>gotcha's</strong> that I need to watch out for?</p> <p>Are there resources, example code and/or documentation available regarding this?</p> <hr> <p>Some other things that I have found out:</p> <ol> <li>Use the following to wrap your C++ headers that need to be used by C code.</li> </ol> <p></p> <pre><code>#ifdef __cplusplus extern "C" { #endif // // Code goes here ... // #ifdef __cplusplus } // extern "C" #endif </code></pre> <ol start="2"> <li>Keep "real" C++ interfaces in separate header files that are not included by C. Think <a href="http://en.wikipedia.org/wiki/Private_class_data_pattern" rel="noreferrer">PIMPL principle</a> here. Using <code>#ifndef __cplusplus #error</code> stuff helps here to detect any craziness.</li> <li>Careful of C++ identifiers as names in C code</li> <li>Enums varying in size between C and C++ compilers. Probably not an issue if you're using GNU tool chain, but still, be careful.</li> <li><p>For structs follow the following form so that C does not get confused.</p> <pre><code>typedef struct X { ... } X </code></pre></li> <li><p>Then use pointers for passing around C++ objects, they just have to be declared in C as struct X where X is the C++ object.</p></li> </ol> <p>All of this is courtesy of a friend who's a wizard at C++.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload