My programming ramblings

Cling a C++11 interpreter

Posted on August 14, 2012 by Sol

A C++11 REPL may sound strange, after all C++ is generally seen as a compiled language. However, any programming language can be implemented as a compiler or as an interpreter and Cling happens to be an interactive C++ interpreter based on LLVM and Clang.

If you’ve ever programmed in a language that can be used in a Read-eval-print-loop or REPL you already know what productivity boost can be to be able to test an idea without waiting for your build system to compile your code. Even with tools like make you need sometimes to wait from a few seconds to a few minutes just to see the effects of some small change in a particular piece of code.

Cling lets you test a C++ piece of code in the same way you would do it in a language like Lisp, Ruby or Python, or almost the same …

Let’s try a trivial C++ example - create an integer and add a constant to this:

See the pattern ? I can test a C++11 snippet directly, without the need to actually create a file, include any header file or even without explicitly printing the result and all this by writing a single line of code.

Cling also lets you write your code in a separate file and load this at the interpreter’s prompt, say that you have a C++ function saved in func.cpp and you want to load this:

What about extending Foo with a new method ? If you try to redefine Foo in Cling you will get an error. You could derive a class from Foo if you need. However, because our initial implementation of Foo uses a private variable state you won’t be able to extend this in a meaningful way. Also, at the time of this writing, Cling seems to not be able to let you unload an existing class, function or variable definition.

Observation: If your class is written in an external file you don’t need to use the raw input command, you will need however to load the class definition and implementation.

If you want to build Cling on your machine you could read the instructions from Cling’s website. I’ve build this on a Mac computer, assuming you have the Command Line Tools from Apple installed this is a resume of how I build Cling:

Disclaimer:All data and information provided on this site is for informational purposes only. solarianprogrammer.com makes no representations as to accuracy, completeness, currentness, suitability, or validity of any information on this site and will not be liable for any errors, omissions, or delays in this information or any losses, injuries, or damages arising from its display or use. All information is provided on an as-is basis. solarianprogrammer.com does not collect any personal information about its visitors except that which they provide voluntarily when leaving comments. This information will never be disclosed to any third party for any purpose. Some of the links contained within this site have my referral id, which provides me with a small commission for each sale. Thank you for understanding.