linux下玩转C++

1.向玩python一样玩C++/C

1.1如何在jupyter中玩C++:

在github上有一个仓库,如下所示:

https://github.com/QuantStack/xeus-cling

xeus-cling 是一个用于C++的Jupyter内核,基于C++解释器和Jupyter协议xeus的原生实现。

目前,支持Mac与Linux,但不支持Windows。

安装也是非常简单,首先安装好Anaconda,在里面创建一个虚拟环境:

conda create -n cling

切换进去:

conda activate cling

给新环境安装jupyternotebook

conda install jupyter notebook

使用conda-forge安装xeus-cling

conda install xeus-cling -c conda-forge

为了加速安装,请记得给Anaconda配置源!

检查是否安装好了内核(kernel):

jupyter kernelspec list

输出:

python3    /home/xxx/anaconda3/envs/cling/share/jupyter/kernels/python3
xcpp11     /home/xxx/anaconda3/envs/cling/share/jupyter/kernels/xcpp11
xcpp14     /home/xxx/anaconda3/envs/cling/share/jupyter/kernels/xcpp14
xcpp17     /home/xxx/anaconda3/envs/cling/share/jupyter/kernels/xcpp17

打开Jupyter Notebook,就可以看到看到kernel了。

启动Jupyter Notebook

jupyter-notebook

1.2如何在Jupyter中玩C?

只需要安装c kernel即可!

可以直接在当前环境中创建c kernel,也可以新开一个环境安装,下面是在当前环境中直接安装。

pip install jupyter-c-kernel
install_c_kernel
jupyter kernelspec list

此时,就输出:

c          /home/light/anaconda3/envs/cling/share/jupyter/kernels/c
python3    /home/light/anaconda3/envs/cling/share/jupyter/kernels/python3
xcpp11     /home/light/anaconda3/envs/cling/share/jupyter/kernels/xcpp11
xcpp14     /home/light/anaconda3/envs/cling/share/jupyter/kernels/xcpp14
xcpp17     /home/light/anaconda3/envs/cling/share/jupyter/kernels/xcpp17

启动Jupyter Notebook

jupyter-notebook

2.C++ 的 debug 工具:dbg-macro

打日志是 C++ 开发中必不可少的一种 debug 方式,dbg-macro 受 Rust 语言中 的 dbg 启发,提供比 printfstd::cout 更好的宏函数。主要有如下特点:

  • 美观的彩色输出(当输出不是交互式终端时,颜色将自动禁用)
  • 兼容 C++11,并且是 header-only
  • 支持基础类型和 STL 容器类型的输出
  • 可以输出文件名、行号、函数名和原始表达式

例如下面的代码:

#include <vector>
#include <dbg.h>

// You can use "dbg(..)" in expressions:
int factorial(int n) {
  if (dbg(n <= 1)) {
    return dbg(1);
  } else {
    return dbg(n * factorial(n - 1));
  }
}

int main() {
  std::string message = "hello";
  dbg(message);  // [example.cpp:15 (main)] message = "hello" (std::string)

  const int a = 2;
  const int b = dbg(3 * a) + 1;  // [example.cpp:18 (main)] 3 * a = 6 (int)

  std::vector<int> numbers{b, 13, 42};
  dbg(numbers);  // [example.cpp:21 (main)] numbers = {7, 13, 42} (size: 3) (std::vector<int>)

  dbg("this line is executed");  // [example.cpp:23 (main)] this line is executed

  factorial(4);

  return 0;
}

效果如下

2.1安装

git clone https://github.com/sharkdp/dbg-macro
sudo ln -s $(readlink -f dbg-macro/dbg.h) /usr/include/dbg.h

这样,你就可以在任何地方使用 dbg.h 了。

在 Arch Linux 上

yay -S dbg-macro

使用 vcpkg

vcpkg install dbg-macro

更多内容详见 官方文档

内容来源

如有侵权,连续我将删除,弄上博客只是方便他人,方便自己

猜你喜欢

转载自blog.csdn.net/qq_42698422/article/details/106603999
今日推荐