Ubuntu – Updating to latest gcc and g++ on Ubuntu 16.04

aptg++gcc

I recently tried to downgrade to gcc 4.7 since a cfd code I was working on didn't compile with the latest gcc version. But after many errors and the code still not compiling I gave up and would like to go back to the latest gcc and g++ compilers however it seems I may have messed something up.

When I do:

sudo update-alternatives --remove-all gcc 
sudo update-alternatives --remove-all g++
sudo apt-get install gcc-6.2 g++-6.2

or even gcc-5.1 g++-5.1 for that matter, it gives me the following error

Reading package lists... Done
Building dependency tree       
Reading state information... Done
E: Unable to locate package gcc-6.2
E: Couldn't find any package by glob 'gcc-6.2'
E: Couldn't find any package by regex 'gcc-6.2'
E: Unable to locate package g++-6.2
E: Couldn't find any package by glob 'g++-6.2'
E: Couldn't find any package by regex 'g++-6.2'

and I also tried doing this before

sudo add-apt-repository ppa:ubuntu-toolchain-r/test
sudo apt-get update
sudo apt-get install gcc-6.2 g++-6.2

but it doesn't seem to work.
Finally when I just do

sudo apt-get install gcc

it says

Reading package lists... Done
Building dependency tree       
Reading state information... Done
gcc is already the newest version (4:5.3.1-1ubuntu1).

I know I still need to install and configure alternatives but doing that doesn't work either as follows

sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-5.3 10
sudo update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-5.3 10
sudo update-alternatives --install /usr/bin/cc cc /usr/bin/gcc 30
sudo update-alternatives --set cc /usr/bin/gcc
sudo update-alternatives --install /usr/bin/c++ c++ /usr/bin/g++ 30
sudo update-alternatives --set c++ /usr/bin/g++
sudo update-alternatives --config gcc
sudo update-alternatives --config g++

Sorry this ended up quite long and please let me know if you need more info. Thanks!

EDIT: I actually got it to work by changing gcc-5.3 to gcc-5 in the above code as that seemed to be what it's called in usr/bin. I will keep it for future reference if anyone faces the same problem.

Best Answer

Run the following commands in sequence. I was getting same error. This worked for me.

sudo add-apt-repository ppa:ubuntu-toolchain-r/test
sudo apt-get update
sudo apt-get install gcc-snapshot
sudo apt-get install gcc-6 g++-6