用Zig来PowerShell终端中替代gcc和g++
目标
- 用zig作为c/c++编译;
- 用VSCode作为编辑器;
- 用Code Runner作为插件完成简易的c/c++编译运行。
环境
需要完成的环境:
- 安装Zig;
- 安装VSCode;
- 给VSCode安装Code Runner插件。
配置
配置Zig作为编译器
VSCode的Code Runner插件默认使用gcc/g++作为编译器,但是我们可以配置它使用zig作为编译器。对于zig来,编译c/c++的命令分别你:
```bash
zig cc -target x86_64-windows-gnu -lc -luser32 -lkernel32 -lshell32 hello.c -o hello_c.exe
zig c++ -target x86_64-windows-gnu -lc -luser32 -lkernel32 -lshell32 hello.cpp -o hello_cpp.exe
```
中间那一堆-lx是开玩笑。
针对PowerShel,我们很容易就可以做一个Alia,假的g++和gc。
PowerShell Aliases
Function gcc {
for ($i = 0; $i -lt $args.Count; $i++) {
if ($args[$i].StartsWith("-o")) {
$args[$i+1] = $args[$i+1] + ".exe"
break
}
}
zig cc $args
}
Function g++ {
for ($i = 0; $i -lt $args.Count; $i++) {
if ($args[$i].StartsWith("-o")) {
$args[$i+1] = $args[$i+1] + ".exe"
break
}
}
zig c++ $args
}
这个函数里,为了适应Code Runner的-o hello,特别把参数中间的文件名加一个exe,方便Windows。
函数定义好,只要在PS中载入,就能完成gcc/g++的替换。还有一个问题就是,如何让每个PowerShell终端都能自动载入这个函数呢?这个问题可以通过配置PowerShell的profile来解决。
PS c:\> echo $profile
C:\Users\User\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
我们就能得到这个文件地址,如果没有这个文件,那就新建一个。
配置Code Runner
接下来就要看到Code Runner的配置了。在VSCode中,我们可以通过Ctrl+Shift+P
打开命令面板,然后输入Code Runner: Configure Code Runner
,就能打开Code Runner的配置文件。在这个文件中,我们可以配置Code Runner的各种参数,我们需要勾选Run In Terminal下面的使用集成终端。
另外,还要把什么运行前存储文件之类的全都点上。
结果
最终的效果就是,我们可以在VSCode中直接按快捷键运行当前活动的C/C++代码了。
PS c:\prjs\zig-crush\> cd "c:\prjs\zig-crush\" ; if ($?) { gcc hello.c -o hello } ; if ($?) { .\hello }
Hello, World!
PS c:\prjs\zig-crush\> cd "c:\prjs\zig-crush\" ; if ($?) { g++ hello.cpp -o hello } ; if ($?) { .\hello }
Hello, World!
结论
- PowerShell很好很强大;
- Zig很方便很好用;
- 无聊的时候,可以折腾折腾。