Ubuntu系统下g++编译致命错误(compilation terminated)的解决咨询
问题背景
以下是逻辑正确的C++代码:
#include <iostream> using namespace std ; // Function call by reference using pointers // writing function for swap system void swapPointer(int* a, int* b){ //temp a b int temp = *a; //4 4 5 *a = *b; //4 5 5 *b = temp; //4 5 4 } int main(){ int x =4, y=5; cout<<"The value of x is "<<x<<" and the value of y is "<<y<<endl; swapPointer(&x, &y); //This will swap a and b using pointer reference cout<<"The value of x is "<<x<<" and the value of y is "<<y<<endl; return 0; }
执行的编译命令:
cd "/media/sulaiman/P:/03_CPP/FULL_CPP/Fucntion in CPP/" && g++ Call_By_Value_&_Referance.cpp -o Call_By_Value_&_Referance && "/media/sulaiman/P:/03_CPP/FULL_CPP/Fucntion in CPP/"Call_By_Value_&_Referance
触发的错误信息:
[1] 24291
[2] 24292
[3] 24293
g++: error: Call_By_Value_: No such file or directory
g++: fatal error: no input files
compilation terminated.
_Referance: command not found
_Referance.cpp: command not found
Referance: command not found
[1] Exit 1 cd "/media/sulaiman/P:/03_CPP/FULL_CPP/Fucntion in CPP/" && g++ Call_By_Value
[2]- Exit 127 Referance.cpp -o Call_By_Value
[3]+ Exit 127 Referance && "/media/sulaiman/P:/03_CPP/FULL_CPP/Fucntion in CPP/"Call_By_Value
一、错误含义
g++: fatal error: no input files:g++未找到指定的编译输入文件,编译流程直接终止。Call_By_Value_: No such file or directory:系统无法定位名为Call_By_Value_的文件/目录。_Referance: command not found:Shell将_Referance识别为独立命令,但系统中不存在该命令。
二、错误原因
核心问题是文件名中的&符号被Shell解析为后台执行控制符,导致原本完整的文件名被拆分为多个无效片段:
- Shell遇到
Call_By_Value_&_Referance.cpp时,会把&当作后台执行标记,将Call_By_Value_和_Referance.cpp拆成两个独立部分,g++因此找不到完整的输入文件。 - 输出文件名和执行命令也因
&被拆分,引发一系列无效命令错误。
三、解决方法
方法1:给含特殊字符的文件名加引号
用单引号或双引号包裹包含&的文件名,避免Shell解析特殊符号:
cd "/media/sulaiman/P:/03_CPP/FULL_CPP/Fucntion in CPP/" && g++ "Call_By_Value_&_Referance.cpp" -o "Call_By_Value_&_Referance" && "./Call_By_Value_&_Referance"
方法2:重命名文件(推荐)
直接修改文件名,移除&这类Shell特殊字符(例如改为Call_By_Value_Referance.cpp),之后用常规命令编译:
cd "/media/sulaiman/P:/03_CPP/FULL_CPP/Fucntion in CPP/" && g++ Call_By_Value_Referance.cpp -o Call_By_Value_Referance && ./Call_By_Value_Referance
建议文件名仅使用字母、数字、下划线和短横线,避免特殊字符引发解析问题。
四、Ubuntu系统重置编译器的步骤
若编译器出现配置错乱、版本冲突等异常,可通过以下步骤重置:
1. 彻底卸载现有编译器组件
sudo apt remove --purge g++ gcc libgcc1 libstdc++6 sudo apt autoremove --purge sudo apt clean
2. 重新安装编译器
安装默认版本的g++:
sudo apt update sudo apt install g++ gcc
如需指定版本(如g++11),可安装对应包:
sudo apt install g++-11 gcc-11
3. 切换默认编译器版本(可选)
若安装了多个版本,用update-alternatives设置默认版本:
sudo update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-11 100 sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-11 100
执行以下命令选择默认版本:
sudo update-alternatives --config g++ sudo update-alternatives --config gcc
内容的提问来源于stack exchange,提问作者Sulaiman hasan Evan

