1. 程式人生 > >Jupyter Notebook 執行 C/C++

Jupyter Notebook 執行 C/C++

Jupyter Notebook 支援非常多的程式語言,而且可以直接執行這些語言的程式碼。要讓 Jupyter Notebook 能夠執行特定語言的程式碼,需要新增對應的核心。具體支援的語言及核心可以檢視該連結: https://github.com/jupyter/jupyter/wiki/Jupyter-kernels 。

今天要講的,是支援在互動模式下執行 C++ 程式碼的 cling 核心。看到官方的示例,我著實感到驚訝,C++程式碼也能夠像 Python 那樣邊寫邊執行?關於其內部的機理我還未深入探究,但最重要的是趕緊裝上 cling 核心,體驗一下互動式執行 C++ 程式碼的快感。

在經過兩天的折騰之後,終於將 C++ 的 cling 核心裝上了。由於我是在 Linux 機器上安裝該核心,主要問題還是編譯過程繁瑣。嘗試了很多方法,包括下載原始碼、手動執行各個編譯過程,結果因種種問題而失敗,不過也從中學到了不少東西。最後克隆了官方的 Github 倉庫,使用其提供的 CPT 工具直接完成編譯,一步到位,非常簡單。

由於 cling 核心依賴於 Python3,因此如果你的機器上安裝的是 Python2 的話,必須先安裝 Python3。安裝 Python3 後,可以順便將其新增到 Jupyter Notebook 核心中,便於以後使用。 
新增 Python3 核心

安裝 Python3:

$ apt-get install python3 python3-pip
  • 1

然後安裝 ipykernel 模組:

python3 -m pip install ipykernel
  • 1

該過程耗時較長,成功後將出現以下提示:

Successfully installed ipykernel ipython traitlets jupyter-client tornado setuptools pexpect simplegeneric prompt-toolkit typing pickleshare pygments jedi decorator ipython-genutils python-dateutil jupyter-core pyzmq backports-abc ptyprocess wcwidth

最後,將 Python 3 核心安裝到 Jupyter Notebook 中:

python3 -m ipykernel install --user
  • 1

OK,此時開啟 Jupyter Notebook,你將會發現已經多了一個 Python3 核心了。 
新增 C++ cling 核心

克隆 cling 的 Github 官方倉庫:

git clone https://github.com/root-project/cling.git
  • 1

在進行編譯操作之前,首先要確保你的機器上已經裝好了 cmake 工具,即能夠直接通過輸入命令 cmake 
執行程式。

如果 cmake 
已經正確安裝,就可以進行以下的操作了。

切換到 cling/tools/packaging/

 目錄下,執行以下兩條命令:

chmod +x cpt.py  
./cpt.py --check-requirements && ./cpt.py --create-dev-env Debug --with-workdir=./cling-build/
  • 1
  • 2

這個過程包含了從網路上獲取原始檔以及編譯,是最為耗時的一個階段,以小時計。

編譯完成後,需要在 python3 中安裝 clingkernel。切換到 cling/tools/Jupyter/ 目錄下,執行

pip3 install kernel/
  • 1

最後一步,往 Jupyter Notebook 中新增 cling 核心,可以根據自己的需要安裝特定 C++ 規範的 cling 核心,例如 cling-cpp11, cling-cpp14, cling-cpp17。

jupyter kernelspec install kernel/cling-cpp17
  • 1

如果沒有其他問題,此時就可以開啟 Jupyter Notebook 感受不一樣的 C++ 程式設計了! 
官方程式碼示例

class Rectangle {  
    private:
        double w;
        double h;

    public:

        Rectangle(double w_, double h_) {
            w = w_;
            h = h_;
        }
        double area(void) {
            return w * h;
        }
        double perimiter(void) {
            return 2 * (w + h);
        }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

Rectangle r = Rectangle(5, 4); 
r.area();


輸出為:
```cpp
(double) 20.000000