Is there a way to compile C++ to C Code?
VisualGBD is a Visual Studio extension that allows you to develop in compile for embedded platforms. It's not free but there is a trial. Worth it in my mind if it works for your application.
https://visualgdb.com
LLVM is a good option.
http://llvm.org/docs/FAQ.html#translatecxx
It handles some code, but will fail for more complex implementations as it hasn't been fully updated for some of the modern C++ conventions. So try compiling your code frequently until you get a feel for what's allowed.
Usage sytax from the command line is as follows for version 9.0.1:
clang -c CPPtoC.cpp -o CPPtoC.bc -emit-llvm clang -march=c CPPtoC.bc -o CPPtoC.c
For older versions (unsure of transition version), use the following syntax:
llvm-g++ -c CPPtoC.cp -o CPPtoC.bc -emit-llvm llc -march=c CPPtoC.bc -o CPPtoC.c
Note that it creates a GNU flavor of C and not true ANSI C. You will want to test that this is useful for you before you invest too heavily in your code. For example, some embedded systems only accept ANSI C.
Also note that it generates functional but fairly unreadable code. I recommend commenting and maintain your C++ code and not worrying about the final C code.
The Comeau site is dead unfortunately. Coherent is built on comeau and might offer some options. They have prebuilt VMs which have been maintained as recent as 2018.
https://www.autometer.de/unix4fun/coherent/#inst_coh
CLang is available but has not been updated in a long time
http://www.softwarepreservation.org/projects/c_plus_plus/cfront/release_3.0.3/source/cfront_3_0_3.tgz
The Comeau compiler seems to be able to do that. From Wikipedia "Rather than produce an executable directly, Comeau C/C++ outputs C code and requires a separate C compiler in order to produce the final program."
I have never tried it, though.
The C++ FAQ has a list of possibilities: Is it possible to convert C++ to C?.
In short, it says that you can't expect this to give you particularly readable code. Think of the complexities involved; multiple inheritance, virtual-function resolution, templates, operator overloading, etc., etc. There's no clean succinct way of expressing these concepts in pure C. If all you're after is compilable C, though, then this is probably the way to go.
You could use the clang C++ frontend to generate llvm bytecode, and use llc
to emit C code, see llc doc, especially the c
option. Both are open source, with BSD like licenses.