我的Ubuntu 18.04.4预装GCC版本为7.5,我想安装一下更新的8版本,并且使用时可以来回切换。
gcc --version
gcc (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0
Copyright (C) 2017 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
g++ --version
g++ (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0
Copyright (C) 2017 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
sudo apt install gcc-8
sudo apt install g++-8
执行
ls /usr/bin/gcc*
可以看到安装目录下已经存在两个不同版本。
/usr/bin/gcc /usr/bin/gcc-ar /usr/bin/gcc-nm /usr/bin/gcc-ranlib
/usr/bin/gcc-7 /usr/bin/gcc-ar-7 /usr/bin/gcc-nm-7 /usr/bin/gcc-ranlib-7
/usr/bin/gcc-8 /usr/bin/gcc-ar-8 /usr/bin/gcc-nm-8 /usr/bin/gcc-ranlib-8
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-8 30
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-7 40
sudo update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-8 30
sudo update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-7 40
**sudo update-alternatives --config gcc **
There are 2 choices for the alternative gcc (providing /usr/bin/gcc).
Selection Path Priority Status
------------------------------------------------------------
* 0 /usr/bin/gcc-7 40 auto mode
1 /usr/bin/gcc-7 40 manual mode
2 /usr/bin/gcc-8 30 manual mode
Press to keep the current choice[*], or type selection number: 2
update-alternatives: using /usr/bin/gcc-8 to provide /usr/bin/gcc (gcc) in manual mode
选择2, 输入2,回车。
sudo update-alternatives --config g++
There are 2 choices for the alternative g++ (providing /usr/bin/g++).
Selection Path Priority Status
------------------------------------------------------------
* 0 /usr/bin/g++-7 40 auto mode
1 /usr/bin/g++-7 40 manual mode
2 /usr/bin/g++-8 30 manual mode
Press to keep the current choice[*], or type selection number: 2
update-alternatives: using /usr/bin/g++-8 to provide /usr/bin/g++ (g++) in manual mode
选择2,输入2,回车。
再查询一下当前版本
gcc --version
gcc (Ubuntu 8.4.0-1ubuntu1~18.04) 8.4.0
Copyright (C) 2018 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
g++ --version
g++ (Ubuntu 8.4.0-1ubuntu1~18.04) 8.4.0
Copyright (C) 2018 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
新建自定义的工程目录,并创建文件:helloworld.cpp
输入以下内容:
#include
using namespace std;
int main()
{
cout << "Hello, world!" << endl;
return 0;
}
打开终端,执行:
g++ helloword.cpp
注意:这里的文件名其实是包含文件路径的。要是不知道文件路径的话可以在敲完g++加上空格之后直接把文件拖进去,系统会自动添加文件路径。默认的输出位置是“主文件夹”,默认输出文件是a.out。可以使用以下格式指定输出的文件名:
g++ 文件名 -o 输出文件名
通过以上步骤编译得到*.out文件以后,可以直接把文件拖到Terminal上,通过按回车键运行。
以上就是Ubuntu系统上最基本的C++编译环境搭建。