从命令行直接使用C++命令

3
我想问一下,是否有办法可以直接在命令行中使用“std::cout <<“Hello world”;”这样的代码。就像如果您已经安装了Python一样。
$python
print 'Hello world'
Hello world
有没有任何方法可以对C++做类似的事情?
4个回答

阿里云服务器只需要99元/年,新老用户同享,点击查看详情
8

有一个名为cling的交互式C++ shell。我没有用过它,但它可能适合你的需求。

这里是更详细的回答:我花了一段时间才构建了cling,主要是因为我没有严格按照说明进行操作,并设置了应该包括的内容。这是我用来构建和安装cling的步骤(对我来说构建发布版本并不起作用):

svn co -r 191429 http://llvm.org/svn/llvm-project/llvm/trunk llvm
cd llvm/tools
svn co -r 191429 http://llvm.org/svn/llvm-project/cfe/trunk clang
git clone http://root.cern.ch/git/cling.git
cd ..
cat tools/cling/patches/*.diff | patch -p0
./configure --enable-targets=host --prefix=/opt/cling
mk -j8
sudo - make install

在这之后,我得到了一个 C++ shell。当然,我的第一次交互并不完全成功,因为 cling 页面说它包含某些头文件,我以为它肯定包含 <iostream>,但实际上并非如此。以下是一个简单的可行交互:

$ /opt/cling/bin/cling 

****************** CLING ******************
* Type C++ code and press enter to run it *
*             Type .q to exit             *
*******************************************
[cling]$ #include <iostream>
[cling]$ std::cout << "hello, world\n";
hello, world
[cling]$ #include <iterator>
[cling]$ std::copy(s.begin(), s.end(), std::ostream_iterator<char>(std::cout));
hello, world
[cling]$ .q

0

我认为不是这样的,C++需要先编译,而Python是一种解释型语言。

因此,您不能有一个调用的脚本。

cout<<"Hello world"; 

在编译代码之前。


0

1
这对大多数实现来说是正确的,但两种语言的语言规范并没有要求它。 (Python确实需要编译器或解释器作为运行时的一部分,以实现“eval”功能。) - James Kanze

0
如果您正在使用GCC和Cygwin或Linux,您可以执行以下操作:
echo -e '#include <iostream>\n int main(void) {std::cout << "Hello world";}'|g++ -xc++ - && ./a.out && rm a.out

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,