2

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

can c use c++ functions somehow?

0

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

can the c++ function declared extern "C" use any other classes in its function body?
5

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

Comments

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.

3 Comments

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 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.
@compile-fan - the C++ code can be called from C but the function is in C++
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.