Search code examples
c++ccompiler-construction

Is C++ built on top of C?


Does C++ code gets converted to C before compilation ?


Solution

  • A few C++ compilers (the original Cfront, Comeau C++) use C as an intermediate language during compilation. Most C++ compilers use other intermediate languages (e.g. llvm).

    Edit: Since there seems to be some misunderstanding about the history: "C with classes" started out using a preprocessor called "Cpre". At that time, it was seen strictly as a dialect of C, not a separate language in itself. In December 1983, people were starting to view it as a separate language, and the name C++ was invented. As it happens, development of Cfront started in April 1983, so a reasonably usable version became available (to a select few) just about the same time as the name "C++" came into use. This appears to be mostly coincidence though.

    As far as producing C as its output, that was really quite common on Unix. Just for example, the Berkeley Pascal compiler and at least a couple of Fortran compilers also produced C as their output.

    There is, however, a huge difference between Cpre and Cfront. Although both produced C as their output, Cpre did virtually no syntax checking of its own -- it looked for a few specific things, and did a relatively mechanical translation on them. It wasn't until the C compiler looked at the result that real syntactical analysis was done. If your code contained a syntax error, it was almost certain that it wouldn't be caught until the C compiler parsed the output from Cpre.

    Cfront, however, did full syntactical analysis of the source code itself, so (short of a bug in its code generator) you'd never see a syntax error from the C compiler. The C compiler was simply used as a code generator so nobody needed to rewrite CFront to accommodate different processors, object file formats, etc.

    If you want to get into more detail, chapter 2 of The Design and Evolution of C++ is devoted almost entirely to the "C with Classes" time frame (and there are various other details about it spread throughout the book).