VSCode 使用 Code Runner 插件無法編譯運行文件名帶空格的文件
- 2021 年 7 月 7 日
- 筆記
- Code Runner, error, Visual Studio Code, Windows
本文同時在我的部落格發布:VSCode 使用 Code Runner 插件無法編譯運行文件名帶空格的文件 – Skykguj ‘s Blog (sky390.cn)
使用 Visual Studio Code 寫 C++ 程式最煩心的是大概就是使用 Code Runner 插件無法編譯運行文件名帶空格的文件了,這個問題困擾了我好久,雖然不影響學習,但太多分隔符總覺得不順眼,於是我仔細研究了一下它。
先創建一個叫 “hello world” 的測試程式,我們再根據 G++ 報錯英文分析一下原因:
g++.exe: error: hello: No such file or directory
g++.exe: error: world.cpp: No such file or directory
g++.exe: error: world: No such file or directory
g++.exe: fatal error: no input files
compilation terminated.
No such file or directory
意思是沒有這樣的文件或目錄,fatal error: no input files
的意思是致命錯誤:沒有輸入文件,然後就編譯已終止了。根據報錯,我們發現 C++ 編譯器是把 hello world.cpp
當成了 hello
和 world.cpp
兩個文件,我的第一反應就是文件名帶空格,要加上雙引號。轉到 Code Runner 插件頁面,點擊設置 -> 擴展設置。
之後,找到 Executor Map,點擊在 setting.json 中編輯。
找到 “cpp”,改成:
"cpp": "cd $dir && g++ \"$fileName\" -o \"$fileNameWithoutExt.exe\" && \"$fileNameWithoutExt.exe\"",
運行 hello world.cpp
,這下編譯成功了,但怎麼輸出文件名了?我又在 CMD 中測試了一下,是能編譯通過並運行程式的,問題立馬鎖定在了 Powershell 上,我想,一定是 CMD 和 Powershell 運行程式的程式碼不同,所以才會出故障。
百度了一下,才發現 Powershell 要在前面加上符號(&),這種叫做調用操作。
加上 & 後,又出現了報錯提示:
原來要加上 “.” 。最終編譯運行程式碼就變成了:
"cpp": "cd $dir && g++ \"$fileName\" -o \"$fileNameWithoutExt.exe\" && & \".\\$fileNameWithoutExt.exe\"",