Click to See Complete Forum and Search --> : C++ lib used in c


theBUSH
April 13th, 2003, 01:03 AM
In linux, if i were to write a lib that used c++ in the lib, but the function that were used to interface with lib were standard c, would i be able to use the lib from a c program?

mwilliamson
April 13th, 2003, 08:56 AM
I don't think you can use any exported classes, but if you export functions with extern "C" I think they will be usable in C. If not, then a DLL will work for sure.

Paul McKenzie
April 13th, 2003, 02:36 PM
Originally posted by theBUSH
In linux, if i were to write a lib that used c++ in the lib, but the function that were used to interface with lib were standard c, would i be able to use the lib from a c program? As long as the functions

a) are "extern C functions" and

b) The arguments to the functions are not references or C++ types

then you won't have a problem calling it from 'C' code.

For a), it doesn't matter what the function does internally or what language it was coded in. As long as the function name is a 'C' function name (not a C++ mangled name), then it can be called from a 'C' program. I have many libraries whose internals are C++, but the function interface is 'C'.

You accomplish this by making the function extern "C". A lot of people believe that this means the function is a 'C' function -- this is not true. All "extern C" does is allow it to have 'C' linkage, which makes the function callable from a 'C' module. The function that is "extern "C" can use as much C++ as you feel like.

As for the arguments, you cannot use reference types in a 'C' function interface, or C++ types (such as std::string, std::vector, etc.).

Regards,

Paul McKenzie