- Mead’s Guide to Upgrading GCC and Clang on Linux
- Adding a repository
- Installing Clang 3.8
- Обновление GCC
- Contents
- Вкратце
- Объяснение обновления GCC
- libtool
- Изменения ABI
- Особый случай C++11 (и C++14)
- Какие пакеты определенно нужно пересобрать?
- Пересборка всего
- Устранение проблем
- пересборка boost
- libstdc++.so.6: version `GLIBCXX_3.4.15′ not found
Mead’s Guide to Upgrading GCC and Clang on Linux
Linux Mint 17 (including 17.1, 17.2, and 17.3) comes with GCC 4.8. To be exact, Linux Mint 17.3 comes with 4.8.4. If you need a later version of the compilers, you can either upgrade the entire distribution to Linux Mint 18.x or install newer versions of GCC alongside of the existing 4.8 version.
Upgrading Mint 17.x to 18.x is straight-forward, although I would recommend a fresh install of 18.x as sometimes the upgrade process doesn’t work as seamless as it should. Installing other versions of the compiler is a little more involved, but it’s a good way of keeping your existing (and functional) Mint 17.x system going. This page will demonstrate how to install newer versions of GCC and Clang.
Most of the work will be done from the command line, as that is the simplest way of doing it. You can just simply copy and paste the command lines listed below into a terminal. This document assumes that you have an up-to-date version of Linux Mint 17.x currently running on your system. It also assumes that you have GCC version 4.8.x and Clang version 3.5. (The default version of Clang is 3.4.) By default gcc is installed but you may have to install g++ manually:
I chose version 3.5 because this will co-exist with Clang version 3.8 nicely. I have discovered (through trial and error) that earlier versions of Clang are removed when installing Clang 3.8. I wanted to keep the older version around because sometimes I like to see how newer versions differ from older versions in the warnings they produce.
I will be updating GCC and Clang on version 17.3 of Linux Mint. To find out which version of GCC is currently enabled, just provide the --version option to gcc:
gcc: (shows version 4.8 and support programs)
OK, so we’ve got a system that has older versions of the compilers installed. Now, it’s time to install newer ones, but we also want to keep the older versions. By default, Linux Mint (as well as other distributions) tries to keep the major versions of software the same throughout the life-cycle of the distribution. This means that, since Mint 17 shipped with version 4.8 of GCC, it will stay at that version with the 17.x versions.
Version 5.x of GCC may be radically different than the 4.x series, so it won’t go into Mint until version 18 of Linux Mint. So, if you want to «get ahead» and install versions that are significantly different (newer), you have to do so manually.
Adding a repository
You simply install it like any other package:
Starting with version 5 of GCC, the version numbering scheme has changed somewhat. You no longer install gcc-5.1 or gcc-5.2. Instead, you simply install gcc-5, and whichever version is the latest one, that’s what you get. This means that you won’t see a third number in the versioning (e.g. 4.8.4). In the old system, going from 4.8.2 to 4.8.4 meant it was a trivial update (small changes, no new features). Going from 4.8 to 4.9 was consider non-trivial. In the new scheme, going from 5.1 to 5.2 is considered trivial. For non-trivial changes, the version will go from 5.x to 6. This means the first number is going to change more rapidly now. In fact, version 6 of GCC is already available.
Installing Clang 3.8
To use version 5 of gcc, you have to type gcc-5. This is all fine and good, but it’s tedious and if you have makefiles that assume gcc (which most do), this won’t work very well. We need to do a few things to allow us to easily switch between GCC and Clang versions as well as just typing the shorter form without explicitly stating the version.
Managing Multiple Versions
I mentioned above that there are lots of ways that you can manage multiple versions of a program. This could be by renaming files (not an ideal solution) or manually creating symbolic links (not a bad idea). Linux has a mechanism already in place to deal with just this situation. It calls multiple versions alternatives. All of the details about how this mechanism works is well beyond the scope of this little tutorial, but I’ll give you a brief introduction.
If you look in /etc/alternatives/ you will probably see lots (maybe hundreds) of links. Here are a few from the Linux Mint 17.3 system I’ve been using for this tutorial (there are actually about 200 links):
Managing all of these alternative links (pointers) is done by a program called, appropriately enough, update-alternatives. There are lots of options with this program, but I’m just going to cover the basics so you can use it effectively. To see what alternatives are available for the FTP program (ftp), just type:
Now, I could do the same thing with g++, as well. But, I don’t really want to use two different versions of gcc and g++ at the same time (e.g. gcc-4.8 and g++-5). I want them to be synchronized so that if I change gcc, then g++ will also change. This is the command to do that:
(When configured for version 4.8)
Note: If you run
Steps to install and enable multiple compilers (this assumes GCC version 4.8/5 and Clang version 3.5/3.8):
- Add the necessary repositories on Linux Mint 17.x for GCC and Clang:
To enable a particular version (for the entire system):
The update-alternatives program basically just automates the creation and updating of the symbolic links. You could certainly do all of this manually (as it was done before we had update-alternatives).
Use this script: update-compilers.sh to perform all of the tasks shown above. After downloading it, make sure it’s executable:
If you want to support 32-bit programs, run this as well:
Update — Install GCC 7.x
If your system already has GCC 5 installed and you’d like to upgrade to GCC 7.x, there is a new script: install-gcc7.sh. You will have to download it and make it executable.
It’s similar to the script above, but installs version 7.x instead. It also doesn’t include Clang in the installation. If you’ve already run the above script, you don’t need the first line in the new script:
You can probably use this script to install any version of GCC (6, 7, 8, etc.) in the future simply by changing the appropriate lines.
Note: This procedure will not remove version 5.x from your computer. It will install version 7.x alongside of version 5.x. This means that you can switch between the two versions at any time using the command:
sudo update-alternatives --config gcc
Update — Install all newer versions
The previous section showed you how to install version 7.x of the GNU gcc compiler. It turns out, it’s trivial to install other later versions as well. I’ve updated the script: install-gcc-all.sh to install versions 6, 7, 8, and 9. If you don’t want to install and configure all of those compilers, just comment out the lines that you don’t want. (To comment out a line, just put a # in front of it.)
The script looks like this:
To change the version of the compiler you want to use, just run the command:
If you don’t use VirtualBox, you can ignore this section.
For example, one of my systems runs Linux Mint 17 (Qiana). It’s been running just fine for years, although it’s getting a little old and at some point it will no longer be supported. I update/upgrade my system every so often like this:
None of the «solutions» I found on the Internet solved the problem. The fix for me was to simply switch the version of gcc to the original version temporarily by running:
This was just a quick introduction to installing newer versions of the compilers, as well as using update-alternatives to manage them. For more information, follow these links:
- The update-alternatives man page.
- Clang’s support for modern C++ constructs.
- GCC’s support for modern C++ constructs.
- Introduction to links under Linux. (PDF)
You can also Google for update-alternatives to find more references and information on using it.
Источник
Обновление GCC
Данный документ показывает пользователям процесс обновления GCC.
Обратите внимание, что понижение версии GCC может иметь нежелаемые побочные эффекты. Обратитесь к секции решения проблем для информации по часто встречаемым проблемам.
Contents
Вкратце
Следующий раздел быстро введет вас в процесс обновления GCC (и того, как просто его сделать). Больше деталей предоставлено в следующем разделе Объяснение обновления GCC.
Большинство обновлений GCC так же просты, как смена версии компилятора (тут с 5.4.0 на 6.4.0) и пересборка libtool :
Проверьте текущую версию и удалите старую версию:
После этого, убедитесь в целостности системы, запустив revdep-rebuild:
Наслаждайтесь новым компилятором!
Объяснение обновления GCC
Обновление GCC всегда считалось какой-то мистикой, с предположениями от «пользователям ничего не нужно делать» до «пользователям нужно дважды пересобрать всю свою систему». Большинство страха, неуверенности и сомнений проистекает из проблем, связанных с несовместимостью ABI. Такое редко происходит в наши дни (и когда происходит, это анонсируется). Но, сначала кратко о libtool .
libtool
Причина, по которой нужно пересобирать libtool после обновления версий gcc это потому, что главной функцией libtool является объединение кода, зависящего от платформы в общем интерфейсе, что позволяет приложениям использовать разделяемые библиотеки без нужды иметь дело с вещами, зависящими от платформы для разделяемых библиотек. Чтобы реализовать эту функцию, скрипт libtool использует различные пути до библиотек, в которых есть жестко заданная информация о версии gcc .
Изменения ABI
ABI, или Двоичный интерфейс приложений, это набор соглашений, используемых всеми инструментами, работающими с бинарным видом программ, например, компиляторы, ассемблеры, линкеры и поддержка рантайма для языков (источник: Бинарная совместимость GCC). Когда ABI, используемый для бинарных приложений и библиотек меняется, появляется риск получить ошибку компоновщика, либо неработающие программы, если только вы не пересоберёте все программы, использующие код C++.
Да, C++, поскольку в большинстве случаев несоответствия обнаруживаются на уровне двоичного интерфейса приложений C++. Если вы обновляетесь до GCC 4.1, или GCC 5.1, вы, вероятно, столкнетесь с проблемами в двоичном интерфейсе. Чтобы избежать этого должна быть запущена команда revdep-rebuild для libstdc++.so.5 (от GCC 3 до GCC 4.1), или libstdc++.so.6 (от GCC 4 до GCC 5.1).
Так почему же это нужно только до GCC 3.4.0/4.1/5? Это потому что с этой версии GCC использует обратно-совместимое ABI, и пересборка приложений и библиотек больше не требуется. Конечно, мы не можем дать вам гарантию, что так будет вечно, но если снова возникнет несоответствие, мы явно опишем этот случай здесь. В этом случае, скорее всего, будет увеличена версия библиотеки libstdc++.so .
Особый случай C++11 (и C++14)
В то время как GCC (или точнее libstdc++) идет большими шагами вперед, гарантируя стабильность ABI, эта гарантия не распространяется на все части C++ в libstdc++. Формально, начиная с версии 3.4, GCC/libstdc++ только гарантируется стабильность C++98/C++03 ABI и не более. Это очень важно для пакетов, которые зависят от C++11. GCC даёт гарантию на стабильность C++11 ABI, начиная только с версии 5.1. Это означает, что переключение (даже незначительные) версии GCC (скажем, от 4.7.3 -> 4.7.4) может привести к поломке ABI для бинарных файлов, собранных из C++11 кода.
Более подробную информацию и некоторые примеры можно найти здесь:
Какие пакеты определенно нужно пересобрать?
В следующей таблице приведены пакеты, которые нужно пересобрать, если они установлены, и причины этой необходимости.
Пакет | Нужно пересобрать, потому что . |
---|---|
sys-devel/libtool | приложение libtool имеет внутри себя вшитые пути к встроенным библиотекам GCC |
sys-devel/llvm | зависит от конкретной версии GCC, могут возникнуть ошибки линкования с другими ебилдами, использующими LLVM (к примеру, media-libs/mesa), если их не пересобрать. |
sys-devel/clang | зависит от конкретной версии GCC, может зависеть от sys-devel/llvm. |
Также известны случаи, когда пакеты должны быть собраны одним и тем же компилятором (к примеру, различные qt-* пакеты). Эти пакеты чаще всего обновляются сопровождающими пакета одновременно (поэтому они всегда будут собираться одной и той же версией GCC). Выборочная переустановка таких пакетов часто сопровождается проблемами.
Пересборка всего
Некоторые люди клянутся, что нужно пересобрать все пакеты на их системе при выходе новой версии GCC. Конечно, в этом нет смысла, так как многие приложения не используют GCC для процесса сборки и установки, и на них вообще не распространяется это изменение.
Это, однако, не означает, что они полностью неправы: новые версии GCC часто предлагают более хорошую поддержку набора инструкций процессора, а это может повлиять на производительность приложений в лучшую сторону.
Кроме таких «небольших» плюсов, пересборка всего с нуля может быть обязательна в некоторых случаях, чтобы исправить проблемы без очевидных причин.
Некоторые проблемы с программами исконно трудны в диагностике, но их можно решить простой пересборкой одного или больше соответствующих пакетов. Если подобная проблема возникла после обновления GCC и сохранилась после применения revdep-rebuild как показано выше (и после пересборки прочих очевидно связанных пакетов), полная пересборка системы может решить этот вопрос.
Самый «безопасный» (но также затратный по времени) способ этого достичь — использование опции —emptytree ( -e ) для emerge, чтобы пересобрать системные пакеты и мир:
Пользователям рекомендуется попробовать этот подход, прежде чем писать о багах, которые могли произойти из-за обновления GCC.
(Заметьте, что команды выше пересоберут пакеты в системном наборе дважды, что необходимо, дабы быть «абсолютно уверенными», что каждый пакет был собран в одинаковой [предположительно] «безпроблемной» среде. Любые проблемы, что сохраняются после этого — действительно баги, о которых нужно сообщить, или серьёзные проблемы с конфигурацией системы.)
Устранение проблем
пересборка boost
Если dev-libs/boost нужно пересобрать, вы получите следующее сообщение об ошибке:
Пересобрать можно с помощью:
libstdc++.so.6: version `GLIBCXX_3.4.15′ not found
В процессе обновлений вы можете встретить ошибку, похожую на следующую:
Это означает, что вы пытаетесь собрать пакет более старой версией GCC, чем собирались библиотеки, от которых зависит пакет. Помните, мы говорили, что C++ ABI обратно совместим? Это так, но означает только, что для сборки приложений и линковки библиотек могут использоваться более новые (или те же самые) версии GCC (по сравнению с версией GCC, использованной для сборки этих библиотек).
Для пересоборки всех зависящих от libstdc++ смотрите пример команды revdep-rebuild в предыдущем разделе.
Источник