compile-fan
compile-fan

Reputation: 17625

How to use c++ functions in c?

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

can c use c++ functions somehow?

Upvotes: 2

Views: 254

Answers (4)

greatwolf
greatwolf

Reputation: 20838

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.

Upvotes: 3

crazyscot
crazyscot

Reputation: 11989

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.

Upvotes: 6

vines
vines

Reputation: 5225

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

Upvotes: 5

sergzach
sergzach

Reputation: 6754

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

Upvotes: 0

Related Questions