cls2cpp.cpp

The cls2cpp.cpp program is a very simple program which can be used to translate .cls files into .cpp files. I had been trying to write some C++ classes with all the code for the methods inside the class definition (just like you see with for example Java and C#). But when classes started to refer to each other, I got some problems, as you cannot call a method on a class whoes interface has not been fully specified.

Usually, the interface definition is given in a .h file, and the implementation in a .cpp file. But there is nothing from stopping you to include a .cpp file. The use of .h files was introduced to facilitate compilation of the sources into separate object files, which are later build into a single executable with the help a linker. But nowadays, with fast computers and enough memory the need for separate compilation is not so strong anymore. (Linking is also a little faster with just one object file.) In that case you simply include the .cpp file.

The problem with the use of separate .h and .cpp files is that they contain a lot of duplicate information, because the method headers are repeated in the .cpp files. I wanted to keep everything in a single file, with all the methods inside the class definitions. So, I designed the .cls file format, which is simply the normal .cpp file, but with the restriction the interfaces of classes need to be fully defined before they are used. The cls2cpp.cpp program, simply takes a .cpp file and reads it three times. The first time, it simply collects the names of the classes and writes a single class name declaration line the .cpp file. The second time, the classes with their members and the headers of the methods are appended into the .cpp file. The third time, the methods with their interface and implementation are copied into the .cpp file. The program also inserts "#line" directives, such that errors are reported with the correct line number from the .cls file.

The program could also be modified such that it would produce separate .h and .cpp. It could also be changed into a program processing multiple files, which would generate a single .h file containing all the class definitions.

Of course, it is a very simple program, and it does not work for all possible C++ class defintions. (For example, it has no support for templates.) But for me it works great.

(See here for an example of usage.)