Scripting In C++

Recently I had to write some scripts to automatize some of my daily tasks. So I had to think about which scripting language to use. You’re probably not surprised when I say I went for C++. After trying several hacky approaches, I decided to try out Cling - a Clang-based C++ interpreter created by CERN.

Cling allows developers to write scripts using C and C++. Since it uses the Clang compiler, it supports the latest versions of the C++ standard.
If you execute the interpreter directly, you'll have a live environment where you can start writing C++ code. As a part of the standard C/C++ syntax, you will find some other commands beginning with '.' (dot).

When you use the interactive interpreter, you can write code like:

#include <stdio.h>
printf("hello world\n");

As you can see, there is no need to worry about scopes; you can just call a function.

If you plan to use Cling as an interpreter for creating your scripts, you need to wrap everything inside of a function. The entry point of the script by default is the same as the file name. It can be customized to call another function. So, the previous example would turn into something like:

#include <stdio.h>

void _01_hello_world() { printf("foo\n"); }

...or the C++ version:

#include <iostream>

void _02_hello_world() { std::cout << "Hello world" << std::endl; }

The examples are quite simple, but they show you how to start.

 

What about Qt?

#include <QtWidgets/qapplication.h>
#include <QtWidgets/qpushbutton.h>

void _03_basic_qt() { int argc = 0; QApplication app(argc, nullptr);

QPushButton button("Hello world"); QObject::connect(&button, &QPushButton::pressed, &app, &QApplication::quit); button.show();

app.exec(); }

But the previous code won't work out of the box - you need to pass some custom parameters to cling:

cling -I/usr/include/x86_64-linux-gnu/qt5 -fPIC -lQt5Widgets 03_basic_qt.cpp

You can customize your "cling" in a custom script based on your needs.

You can also load Cling as a library in your applications to use C++ as a scripting language. I'll show you how to do this in one of my next blog posts. Cheers!


Blog Topics:

Comments