user66875
user66875

Reputation: 2608

Using a C++ class in C code

I was under the impression that it should be possible to mix c and c++ code, but looks like I was wrong.

I'm having a bunch of existing C code and have written a class in C++ that I would like to use in the existing C code.

Is that even possible?

Upvotes: 1

Views: 178

Answers (3)

You can't use classes from C code, because classes don't exist in C.

However, you can define a bunch of global functions that access your class, and then you can access those functions from C.

Upvotes: 2

QuentinUK
QuentinUK

Reputation: 3077

You can mix the two and then compile the result as C++.

If you have a C++ class that you want to use in C then you could remove all the member functions and rewrite then with an extra parameter being a ptr to a structure. More advance C++ features wouldn't be so easy to incorporate in C.

Upvotes: 0

Hatted Rooster
Hatted Rooster

Reputation: 36483

C++ is not a superset of C and thus not all C code is valid C++ code. This is even more true for C++ code in a C compiler. All language additions C++ has are not valid C (classes, generic programming, namespaces). What you could do is compile the result code with a C++ compiler and fix cases where code that was valid for a C compiler isn't for a C++ compiler.

Upvotes: 2

Related Questions