How to install gcc on ubuntu
How to install gcc on ubuntu
Как установить компилятор GCC в Ubuntu 18.04
How to Install GCC Compiler on Ubuntu 18.04
В этом руководстве описаны шаги, необходимые для установки компилятора GCC в Ubuntu 18.04. Мы покажем вам, как установить стабильную версию дистрибутива и последнюю версию GCC.
Те же инструкции применимы для Ubuntu 16.04 и любого дистрибутива на основе Ubuntu, включая Kubuntu, Linux Mint и Elementary OS.
Прежде чем вы приступите
Установка GCC на Ubuntu
Репозитории Ubuntu по умолчанию содержат метапакет с именем, build-essential который содержит компилятор GCC и множество библиотек и других утилит, необходимых для компиляции программного обеспечения.
Выполните следующие шаги, чтобы установить компилятор GCC Ubuntu 18.04:
Начните с обновления списка пакетов:
Установите build-essential пакет, набрав:
Вы также можете установить справочные страницы об использовании GNU / Linux для разработки:
Версия GCC по умолчанию, доступная в репозиториях Ubuntu 18.04 7.4.0 :
Вот и все. GCC теперь установлен в вашей системе, и вы можете начать его использовать.
Компиляция примера Hello World
Скомпилировать базовую программу на C или C ++ с помощью GCC довольно просто. Откройте текстовый редактор и создайте следующий файл:
Сохраните файл и скомпилируйте его в исполняемый файл с помощью следующей команды:
Это создаст двоичный файл с именем hello в том же каталоге, где вы запускаете команду.
Запустите hello программу с помощью:
Программа должна напечатать:
Установка нескольких версий GCC
В этом разделе приведены инструкции по установке и использованию нескольких версий GCC в Ubuntu 18.04. Новые версии компилятора GCC включают поддержку новых языков, лучшую производительность и расширенные функции.
В следующем примере мы установим последние три версии GCC и G ++.
Сначала добавьте ubuntu-toolchain-r/test PPA в вашу систему с помощью:
Установите нужные версии GCC и G ++, набрав:
Позже, если вы захотите изменить версию по умолчанию, используйте update-alternatives команду:
Команда создаст символические ссылки на определенные версии GCC и G ++.
Вывод
Вы успешно установили GCC на свой Ubuntu 18.04. Теперь вы можете посетить официальную страницу документации GCC и узнать, как использовать GCC и G ++ для компиляции программ на C и C ++
Установка GCC в Ubuntu
Большинство программ в Linux написаны на C или С++, и если вы хотите собирать их из исходников, то вам обязательно понадобиться компилятор, также он понадобиться, если захотите начать писать свои программы на одном из этих языков.
Набор компиляторов GCC
В базовую поставку компилятора входят такие программы:
Все эти пакеты являются зависимостями пакета build-essential, поэтому для установки всего необходимого достаточно установить этот пакет.
Установка GCC в Ubuntu
Если вас устраивает текущая версия GCC, которая есть в официальных репозиториях дистрибутива, то вам достаточно установить пакет build-essential. Для этого выполните команду:
После завершения установки все необходимое для компиляции программ будет установлено. И вы сможете использовать компилятор. Рассмотрим версии и расположение файлов компилятора:
whereis gcc make
Далее установите сам компилятор:
Это не заменит ваш текущий компилятор на новый. В системе просто появятся 2 версии компиляторов gcc-11 и g++11, которые вы можете использовать для своих программ. Это лучший вариант на данный момент, но если вы хотите все же сделать gcc-9 компилятором по умолчанию, выполните:
Готово, теперь вы можете проверить версию gcc-6:
Установка GCC в Ubuntu завершена, и можно переходить к сборке программ. Для удаления компилятора достаточно удалить пакет build-essential при помощи команды:
Использование GCC в Ubuntu
Рассмотрим пример компиляции минимальной программы hello.c для освоения работы с gcc. Вот код программы, откройте любой текстовый редактор и сохраните его в файле с названием hello.c:
#include
int main(void) <
printf(«Hello, world!\n»);
return 0;
>
Теперь запустим сборку программы:
Когда сборка программы будет завершена, на выходе появится файл с названием a.out. a.out –это имя исполняемого файла, которое по умолчанию, сгенерировано при помощи gcc. Далее можно запустить данный файл:
Готово, компилятор прекрасно работает в системе, и теперь можно писать свои программы или собирать чужие.
Выводы
В этой статье мы рассмотрели, как установить gcc в Ubuntu 20.04, это один из самых популярных компиляторов для этой операционной системы. И устанавливается он очень просто, если у вас остались вопросы, спрашивайте в комментариях!
На завершение видео с демонстрацией самого процесса:
How to install GCC on Ubuntu 20.04
Prerequisites
Equivalent to the installation of other packages on ubuntu, GCC also postulates some prerequisites before installing it on ubuntu 20.04. Those requirements encompass the availability of enough space for some latest binary files. Also, it is an inherent requirement for any form of installation to log-in the system via root user or through the user entailing the sudo privileges.
Installation Procedure
It has become excessively quick to download the GCC compiler on ubuntu. The reason is justified by the fact that the Linux system’s depository also contains the packages for build-essentials. Through these packages, you can conveniently download the GCC compiler. Primarily you can find these packages in the repository through the meta-package. If you want to access the GCC compiler after a convenient installation, then you should opt for the development package. That will assist you in downloading all the build-essentials of GCC in your system in a single go.
Installation Steps
You can achieve the successful installation of GCC in your ubuntu by three major steps. These steps are so easy that even if you are a beginner, you can handily use the commands for an effective installation. The steps for the installation of the GCC compiler on your Ubuntu 20.04 are as follows:
System Packages Updating
In this step, use the simple and fundamental sudo commands to update and upgrade your existing packages. By inputting these commands, you can update your system packages. the sudo commands for this purpose are:
Although the upgrade command of sudo is not mandatory, make sure to run the command for updating your system packages. It is a crucial step because, without updating, you can precisely access the level of your system packages.
Installation of Development Package
This is the second step for the installation. Some people just leave the process after this step, and it is quite alright. The steps after this one are just to ensure the installation, so professional programmers usually install the GCC package using the first two steps only. But for beginners, it is recommended to perform all the steps just to be sure that you have successfully installed the compilation of GCC.
Dwell upon the fact that this command of sudo assist in the installation of the development package that itself is a build-essential of GCC compiler. Apply the following command of sudo to install the development package.
After this command, you will see an output window that will tell you about the successful installation. The output will also reveal all the additional packages that you have downloaded along with your development package. You will also witness the packages suggested by the system for downloading along with the recommendation of a manual page to understand the GCC development on your Ubuntu 20.04 fully. The output window will also ask you to type Y (Yes) for the continuation of the installation. Just press Y and then press Enter, and you will successfully install the GCC.
Downloading of Manual Pages
This step is optional because it doesn’t play any functional role in the overall installation of GCC. But it can assist you in understanding the usance of GNU for effective development. Type the following command if you want to download the manual pages.
With this, you will get a hold of the manual pages constituting the instructions for development.
Verification of GCC.
Now, this is the last step. You can skip it if you are a professional or if you are sure that the compiler has been installed. To verify your recently installed GCC compiler on ubuntu input this command in your system terminal:
It is important to know that you can also use this command at the beginning of the process if you have existing GCC on your system. It will tell you the existing version of the GCC compiler then.
Conclusion
This guide is well-detailed so that even if you are a beginner in the field of programming, you can still install GCC with efficiency. If you notice the output window after every command keenly, then you’ll know what is going on, what are the supplements downloads, and what you need to do further for assurance of your installation package. Also, if you are a beginner, then ensure the implementation of the last two steps to be on the safe side.
About the author
Younis Said
I am a freelancing software project developer, a software engineering graduate and a content writer. I love working with Linux and open-source software.
How To Install GCC Compiler On Ubuntu?
GCC (GNU Compiler Collection) is a collection of tools used to compile different programming languages source code into binary, executables, or libraries. GCC supports a lot of programming languages like C, C++, Java, Objective-C, Go, Fortran, Ada, etc. A lot of open-source projects use the GCC to compile source code to binary. In this tutorial, we will learn how to install GCC compiler set in Ubuntu and compile sample C applications into binary.
Install GCC on Ubuntu
We can install the GCC with the following apt command for Ubuntu, Debian, Mint etc. We also provide the sudo command for root privileges.
Check GCC Version
After the GCC installation is completed or at any time we can check the installed GCC version. The –version option is used to display the GCC version.
Install GCC Build Essential and C++ Compiler on Ubuntu
GCC is very extensive tool set where there are a lot of extensions about it. The build essentials is a set of tools which provides extra libraries for GCC and also the C++ compiler named g++. The build essentials is named as build-essential and can be installed like below.
Compile Example C Application
After installing the GCC we can check the installation and compile a sample C application.
We will compile this C application with the GCC command. The -o option is used to specify the created binary name and the source file name.
Updating GCC on Ubuntu
The GCC is a very active project and updated regularly. In every update, new features and bug fixes are provided. The installed GCC can be easily updated in Ubuntu by using the “apt update” command like below.
Ubuntu Documentation
Installing the GNU C compiler and GNU C++ compiler
To install the gcc and g++ compilers, you will need the build-essential package. This will also install GNU make.
build-essential contains a list of packages which are essential for building Ubuntu packages including gcc compiler, make and other required tools.
Now, you should able to compile software using C / C++ compilers.
To install the manpages for c and c++ development, install the manpages-dev package.
Installing the GNU Java compiler
Note that GNU’s Java compiler is not the same as the one developed and distributed by Sun Microsystems, and will not provide Java to the firefox browser. For that, please see Java. To install gcj, the GNU Java compiler, install the following package: gcj.
To install the GNU Java bytecode interpreter, you need the gij package.
To have gcj compile to executables, install libgcj6-dev (otherwise an error during compilation occurs: libgcj.spec: No such file or directory). Use synaptic to install libgcj6-dev.
Installing the GNU Fortran compilers
Installing the GNU autotools
To install autoconf and automake, you need the autoconf and automake packages.
Apt-get will tell you to explicitly choose a version of automake. If, for example, you decide to use automake1.9, you need to specify the version, such as the automake1.9 package.
32-bit Builds on AMD64
The GNU compilers have options that allow them to create 32-bit object and executable files on 64-bit operating systems, and vica versa. The critical options are -m32 (to build 32-bit) and -m64 (to build 64-bit).
These options will be present when you install the compiler of your choice. However, they won’t actually work unless you install several additional packages.
The first thing you will need is the multilib package for the compiler you are using. For example, to add multilib support to the default version of g++ (4.1 in gutsy), you would install
The multilib packages are compiler runtime packages. Now, you need 32-bit (or 64-bit) versions of whatever libraries you need to link your application program. 64-bit packages have names that start with lib64. Install these on 32-bit systems to support 64-bit builds. 32-bit packages have names that start with lib32. Install these on 64-bit systems to support 32-bit builds. Whatever else you are doing, you will probably need
Installing the Intel Compiler Suite Professional Edition 10.x
Using the Intel compilers for C, C++, and FORTRAN requires installing 32-bit libraries for Ubuntu if you are using a 64-bit system. Please ensure you have these packages:
gcc, build-essential, libc6-dev (see above)
ia32-libs, g++-multilib, and libc6-dev-i386 (for 64-bit systems)
32-bit packages starting with lib32 (for 64-bit systems)
alien and rpm for installing the RPM packages that Intel distributes.
libstdc++5 and libstdc++5-3.3-dev for good measure because Intel’s builds depend on these runtimes.
before you attempt installing the Intel Compiler Suite.
Get the License Number and Extract to a path without spaces
Ensure that you have obtained the license number for your installation and extracted the downloaded installation archive into a path that does not contain any spaces. This last statement is utterly important. The installer script that comes with the package has a bug that does not allow you to install the compiler suite if you have any spaces in the installer script path.
On 64-bit systems you may also need to issue these commands
because the chklic_32_64 license checking utility from Intel dynamically links to these libraries.
Once you’re done preparing to install the compiler suite, it’s time to go to the installer directory and install the compiler (be sure to also read through accompanying documentation; e.g., README, INSTALL.txt):
Run the Installation Script
After installing the compiler, you need to tell your shell the location of these executables by adding their parent paths to the PATH environment variable.
Edit /etc/bash.bashrc to add the installation path to the PATH environment variable
Where 10.1.012 is the version of the compiler suite installed.
Installing the X11 development compilers
Install script for X11 development libs
InstallingCompilers (последним исправлял пользователь andrius-zilenas 2012-08-10 10:18:50)
The material on this wiki is available under a free license, see Copyright / License for details
You can contribute to this wiki, see Wiki Guide for details