我是C ++程序员。我想将编译,运行和调试程序的任务自动化为一个简洁的PowerShell脚本。但它意外地抛出了无关的错误,我不知道为什么。
该程序将C ++文件作为输入,生成一个已编译的.exe文件并立即运行该程序。它还需要其他一些调试选项。
if (!($args.count -ge 1)) {
Write-Host "Missing arguments: Provide the filename to compile"
exit
}
$isRun = 1
$EXE_NM = [IO.Path]::GetFileNameWithoutExtension($args[0])
$GPP_ARGS = "-o " + $EXE_NM + ".exe"
$count = 0
foreach ($op in $args) {
if ($op -eq "-help" -or $op -eq "-?") {
Write-Host "Format of the command is as follows:-"
Write-Host "cpr [filename.cpp] {additional files}"
Write-Host "{-add [compiler options] (all options of -add should be in double quotes altogether)}"
Write-Host "[-d (short for -add -g)] [-nr (do not run automatically)]"
exit
} elseif ($op.Contains(".cxx") -or $op.Contains(".cpp")) {
$op = """$op"""
$GPP_ARGS += " " + $op
} elseif ($op -eq "-add") {
if (($count+1) -ne $args.Count) {
$GPP_ARGS += " " + $args[$count+1]
}
} elseif ($op -eq "-d") {
$GPP_ARGS += " -g"
} elseif ($op -eq "-nr") {
$isRun = 0
}
$count += 1
}
$err = & g++.exe $GPP_ARGS 2>&1
if ($LastExitCode -eq 0) {
if ($isRun -eq 1) {
if ($isDebug -eq 1) {
gdb.exe $EXE_NM
} else {
iex $EXE_NM
}
}
if ($err.length -ne 0) {
Write-Host $err -ForegroundColor "Yellow"
}
} else {
Write-Host "$err" -ForegroundColor "Red"
}
例如:当我尝试cpr.ps1 HCF.cpp
时,它会抛出以下错误:
g ++。exe:致命错误:没有输入文件编译终止。
我确保当前工作目录中存在.cpp文件。
答案 0 :(得分:0)
我推荐使用make
而不是编写自己的构建脚本。一个简单的可重用Makefile并不难写:
CXX = g++.exe
CPPFLAGS ?= -O2 -Wall
# get all files whose extension begins with c and is at least 2 characters long,
# i.e. foo.cc, foo.cpp, foo.cxx, ...
# NOTE: this also includes files like foo.class, etc.
SRC = $(wildcard *.c?*)
# pick the first file from the above list and change the extension to .exe
APP = $(basename $(word 1, $(SRC))).exe
$(APP): $(SRC)
$(CXX) $(CPPFLAGS) -o $@ $<
.PHONY: run
run: $(APP)
@./$(APP)
.PHONY: debug
debug: $(APP)
@gdb $(APP)
.PHONY: clean
clean:
$(RM) $(APP)
make
构建程序(如果需要)。 make run
在构建程序后执行该程序。 make debug
在gdb
中运行该程序。 make clean
删除该程序。
您可以通过定义环境变量来覆盖默认的CPPFLAGS:
$env:CPPFLAGS = '-g'
make