背景
Code Runner是一款VS Code上的代码运行插件,响应速度比软件自带调试速度快,唯一缺点就是无法Debug。
之前的使用过程中,通过配置该插件的settings.json文件,在成功执行程序编译链接出的exe文件后,可以用del指令删除exe文件,保证文件夹内文件都是清一色cpp文件。
但是在使用过程中,又发现code runner运行的cpp文件名不能包含空格、括号等字符,使用起来体验感非常差。
在拜读多篇博客之后,又终于找到了一个一劳永逸的解决办法,特此将自己踩的坑记录一下。
方法:通过修改code runner配置文件settings.json,将filename前后加入’'来保证读入文件名为字符串
之前删除exe生成文件的博客(一文解决在ubuntu下,删除vscode插件code runner执行时c/cpp文件生成的exe文件)中提到,原本的配置文件内容为:
"code-runner.executorMap": {
"c": "cd $dir && gcc $fileName -o $fileNameWithoutExt.exe && $dir$fileNameWithoutExt.exe && del $dir$fileNameWithoutExt.exe",
"cpp": "cd $dir && g++ $fileName -o $fileNameWithoutExt.exe && $dir$fileNameWithoutExt.exe && del $dir$fileNameWithoutExt.exe"
}//win下
这串代码的含义是进行三个由&&
连接的指令
第一个指令为cd $dir
,即转到当前cpp源文件目录下
第二个指令为g++ $fileName -o $fileNameWithoutExt.exe
,即编译文件
第三个指令为$dir$fileNameWithoutExt.exe
,即对控制台输入exe文件绝对路径,执行文件
第四个指令为del $dir$fileNameWithoutExt.exe
,即在运行完文件后,删除编译出的执行文件
那么在这个过程中,如果cpp文件的fileName是hello world
那么编译的时候会遇到空格符结束读入,换言之就会只读入hello
解决的方法是在fileName左右两边加上",这样就可以用转义字符的方法,将文件名用双引号括起。
但是这里的第三条指令需要额外修改,即加上(&)符号,含义为调用文件,因此该配置文件内容需要改为:
"code-runner.executorMap": {
"c": "cd $dir && gcc \"$fileName\" -o \"$fileNameWithoutExt.exe\" && & \"$dir$fileNameWithoutExt.exe\" && del \"$dir$fileNameWithoutExt.exe\"",
"cpp": "cd $dir && g++ \"$fileName\" -o \"$fileNameWithoutExt.exe\" && & \"$dir$fileNameWithoutExt.exe\" && del \"$dir$fileNameWithoutExt.exe\""
}//win下
后续补充
- 10.23日,发现文件名前缀有
[
或者]
都不能成功执行del指令