1

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?

user66875
  • 2,772
  • 3
  • 29
  • 55
  • 2
    how about compile everything as C++ – David Haim Nov 29 '15 at 19:33
  • 3
    You have to write a wrapper around your C++ class that will be accessible from C. This usually means creating a wrapper `struct` that has a pointer to the C++ instance of a class, and a function for each class member function that takes this wrapper `struct` and calls the C++ member function from C++ code. – Daniel Kamil Kozar Nov 29 '15 at 19:33
  • Note that while you can compile it as C++, mixing C and C++ rarely results in quality code. They are different languages and should be treated as such. – user4520 Nov 29 '15 at 19:42
  • Even if you wrap the C++ class, you still have to be pretty careful, since if you compile your `main()` function as C then constructors aren't going to be run on static instances, for instance, and depending on what facilities your C++ class uses, you might not even know that you're using some of these. – Crowman Nov 29 '15 at 20:17

3 Answers3

2

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.

Hatted Rooster
  • 35,759
  • 6
  • 62
  • 122
2

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.

user253751
  • 57,427
  • 7
  • 48
  • 90
0

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.

QuentinUK
  • 2,997
  • 21
  • 20
  • You cannot compile C as C++. If you do that, you never wrote C code, you wrote C++ code. Please do not confuse these two languages. – fuz Nov 29 '15 at 20:38