VSCode 使用 Code Runner 外掛無法編譯執行檔名帶空格的檔案

Skykguj發表於2021-07-07

本文同時在我的部落格釋出: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 當成了 helloworld.cpp 兩個檔案,我的第一反應就是檔名帶空格,要加上雙引號。轉到 Code Runner 外掛頁面,點選設定 -> 擴充套件設定。

Code Runner 外掛頁面

擴充套件設定

之後,找到 Executor Map,點選在 setting.json 中編輯。

Executor Map

找到 "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\"",

result

相關文章