2

C++ can use c functions by extern "C",

can c use c++ functions somehow?

compile-fan
  • 16,885
  • 22
  • 59
  • 73

4 Answers4

6

Not really. You can write a "C-compatible" function in C++, that is to say outside of any class or namespace and whose prototype does not use classes or references. If declared extern "C" then you could call such a function from C. The function could then go on to make use of whatever C++ features were useful for it.

crazyscot
  • 11,819
  • 2
  • 39
  • 40
5

Just the same way, if you declare a C++ function as extern "C", C will be able to link with it.

vines
  • 5,160
  • 1
  • 27
  • 49
3

When it comes to functions in c++, there are two types that come to mind: plain-old stand alone functions and member functions that're part of a class. There is no way to use the second type directly in C since it has no notion of an 'object'. Remember member functions have an implicit 'this' as a hidden first parameter.

You can, however, use the first type of function in C if you decorate it with the extern "C" declaration as part of the function prototype. This is needed to tell the C++ compiler to not 'mangle' the function name when you compile your source.

greatwolf
  • 20,287
  • 13
  • 71
  • 105
  • what if the plain-old stand alone functions uses other classes in its function body,can it still be used directly in c? – compile-fan May 28 '11 at 09:59
  • @compile-fan that is possible but only if you compiled that function in C++ mode and then link into your C code afterwards as a library or object file. The key observation here is you have to keep C++ specific code isolated behind that boundary. – greatwolf May 28 '11 at 10:02
  • @compile-fan - the C++ code can be called from C but the function is in C++ – mmmmmm May 28 '11 at 10:03
0

C can use C++ functions only as functions from an external library.

Better way is to compile your C code with help of C++ compiler. Look here, please: http://www.velocityreviews.com/forums/t288284-calling-c-from-c.html

sergzach
  • 6,578
  • 7
  • 46
  • 84