Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C/C++ interactive interpreter

I would like to know if there is an equivalent to python interpreter for C/C++ :

$ python
Python 2.7.3 (default, Mar 13 2014, 11:03:55)
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> "   test\n\n ".strip()
'test'
>>> import re
>>> re.search('([\d\.]*).tgz', 'package-2.1.5.tgz').group(1)
'2.1.5'

Up to now, I have always used a dummy bash script for this purpose. It is not interactive, but it prevents from creating a C++ file with main etc. to check the result of a single or some commands.

I am pretty sure we can do it in gdb or eclipse somehow, or it exists somewhere else hidden in a package, so if you know interesting stuff around that issue, I would appreciate to know it. Thanks, and have a nice day.

 $ cat cInterpreter.sh
 #!/bin/bash

function usage {
  cat <<EOF
USAGE:
$0 '<semi-colon separated includes>' '<semi-colon separated commands>'

EXAMPLE:
$0 'arpa/inet.h' 'printf("%04x\n", htons(5294));'

EOF
}

if [ $# -ne 2 ] || [ "$1" = "--help" ]; then
  usage
  exit 0
fi

includes=$1
commands=$2

g++ -Wall -x c++ - -o /tmp/cInterpreter.bin <<EOF &&
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

$(tr ';' '\n' <<< $includes | xargs -I{} echo "#include <{}>")

int main() {
  $commands;
  return 0;
}

EOF
 /tmp/cInterpreter.bin

$ cInterpreter.sh 'arpa/inet.h' 'printf("%04x\n", htons(5294));'
ae14
like image 237
user1556814 Avatar asked Dec 08 '25 09:12

user1556814


2 Answers

You've got cling, it's not perfect, but it's a c++ repl

http://blog.coldflake.com/posts/On-the-fly-C++/

git clone http://root.cern.ch/git/llvm.git src
cd src
git checkout cling-patches
cd tools
git clone http://root.cern.ch/git/cling.git
git clone http://root.cern.ch/git/clang.git
cd clang
git checkout cling-patches

cd ../..
./configure --enable-cxx11
make
sudo make install

$ cling -Wc++11-extensions -std=c++11

****************** CLING ******************
* Type C++ code and press enter to run it *
*             Type .q to exit             *
*******************************************
[cling]$ #include <arpa/inet.h>
[cling]$ htons(5294)
(uint16_t) 44564
[cling]$ printf("%04x\n", htons(5294))
input_line_5:2:2: error: use of undeclared identifier 'printf'
 printf("%04x\n", htons(5294))
 ^
[cling]$ #include <stdio.h>
[cling]$ printf("%04x\n", htons(5294))
ae14
like image 83
user1708860 Avatar answered Dec 09 '25 23:12

user1708860


Tiny C Compiler (http://bellard.org/tcc) supports interpreter mode. Though it's C only.

like image 28
Matt Avatar answered Dec 09 '25 22:12

Matt