Меню Рубрики

Установка gcc для centos

Как установить компилятор GCC на Ubuntu 18.04

Главное меню » Операционная система Ubuntu » Как установить компилятор GCC на Ubuntu 18.04

В этой статье рассматриваются шаги, необходимые для установки компилятора GCC в Ubuntu 18.04. Мы покажем вам, как установить стабильную версию дистрибутива и последнюю версию GCC.

Те же инструкции применимы для Ubuntu 16.04 и любого дистрибутива на основе Ubuntu, включая Kubuntu, Linux Mint и Elementary OS.

Предпосылки

Чтобы иметь возможность добавлять новые репозитории и устанавливать пакеты в вашей системе Ubuntu, вы должны войти в систему как пользователь с привилегиями sudo.

Установка GCC на Ubuntu

Репозитории Ubuntu по умолчанию содержат метапакет с именем build-essential, который содержит компилятор GCC и множество библиотек и других утилит, необходимых для компиляции программного обеспечения.

Выполните следующие шаги для установки компилятора GCC Ubuntu 18.04:

  1. Начните с обновления списка пакетов:
  2. Установите пакет build-essential, набрав:

Команда будет установить несколько новых пакетов , включая gcc, g++и make.

Вы также можете установить страницы руководства по использованию GNU/Linux для разработки:

Чтобы проверить, что компилятор GCC успешно установлен, используйте команду gcc –version, которая напечатает версию GCC:

Версия GCC по умолчанию, доступная в репозиториях Ubuntu 18.04 7.4.0:

Вот и все. GCC теперь установлен в вашей системе, и вы можете начать использовать его.

Компиляция примера Hello World

Компиляция базовой программы на C или C++ с использованием GCC довольно проста. Откройте ваш текстовый редактор и создайте следующий файл:

Сохраните файл и скомпилируйте его в исполняемый файл с помощью следующей команды:

Это создаст двоичный файл с именем hello в том же каталоге, где вы запускаете команду.

Выполните программу hello с:

Установка нескольких версий GCC

В этом разделе мы предоставим инструкции о том, как установить и использовать несколько версий GCC в Ubuntu 18.04. Новые версии компилятора GCC включают поддержку новых языков, лучшую производительность, расширенные функции.

На момент написания этой статьи стандартные репозитории Ubuntu включали в себя несколько версий GCC, от 5.x.xдо 8.x.x. Последняя версия GCC 9.1.0 доступна в Ubuntu Toolchain PPA.

В следующем примере мы установим последние три версии GCC и G ++.

Сначала добавьте ubuntu-toolchain-r/testPPA в вашу систему с помощью:

Установите нужные версии GCC и G ++, набрав:

Команды ниже настроят альтернативу для каждой версии и свяжут с ней приоритет. По умолчанию используется версия с наивысшим приоритетом, в нашем случае это gcc-9.

Позже, если вы хотите изменить версию по умолчанию, используйте команду update-alternatives:

Вам будет представлен список всех установленных версий GCC в вашей системе Ubuntu. Введите номер версии, которую вы хотите использовать по умолчанию, и нажмите Enter.

Команда создаст символические ссылки на конкретные версии GCC и G ++.

Заключение

Вы успешно установили GCC на Ubuntu 18.04. Теперь вы можете посетить официальную страницу документации GCC и узнать, как использовать GCC и G ++ для компиляции ваших программ на C и C ++.

Если вы столкнулись с проблемой или у вас есть отзыв, оставьте комментарий ниже.

Если вы нашли ошибку, пожалуйста, выделите фрагмент текста и нажмите Ctrl+Enter.

источник

How To Install GCC on CentOS 6

CentOS follows the development of Red Hat Enterprise Linux (RHEL). RHEL strives to be a stable server platform, which means that it does not rush to include the latest versions of every software package.

As of the writing of this article, CentOS 6 officially distributes GCC v4.4.7. However, GCC v5.1 was recently released. Before that, v4.9.2 was available.

The official suggestion to needing a more recent version of GCC is that you should consider a different UNIX distribution which is more focused on supporting the latest versions of software packages.

Fortunately, you are able to install a more recent version of GCC on CentOS, leaving the older version still installed. This deviates from purely using the officially distributed software, but sometimes you may feel like you have little choice. You can run into some complications; for example, if you are installing third party kernel modules, they must be compiled using the same version of GCC used to build your kernel.

This article describes how to install the CentOS 6 officially supported version of GCC, and how to install a newer version as well. This article assumes that you have a freshly installed CentOS 6 VPS, although you can certainly follow the instructions on an existing VPS.

Install an officially supported (older) version of GCC

Even if you want to install a newer version of GCC from source, GCC itself is written in C++. Therefore, you first have to install an older C++ compiler.

Login to your VPS, either by clicking «View Console» in the Vultr control panel, or by SSH, if you have set that up.

(b) Create your own user account, and give it a password.

(c) Allow your user account to execute commands with root privileges, through the sudo command.

(d) Log out as root, and login to your user account.

Install the CentOS 6 GCC packages. This will ask you if you want to install around 11 packages, due to dependencies.

Check the installed versions, and show their locations.

Install a newer version of GCC from source

If you only want the CentOS officially supported version of GCC, you’re all set. If you need a more recent version of GCC, continue on.

IMPORTANT! First, complete the steps above to install an older binary version of GCC.

Install additionally required packages. This will ask you if you want to install around 41 packages.

Decide which version of GCC you want to install. This command will show you the «tags» for each of the versions available.

Get the source of the version of GCC you want. This will run for a few minutes. The rest of this article is written for gcc-5_1_0_release/ and will download the sources into

Get the source of additional prerequisites. Using v5.1.0, this downloads sources and adds them to the GCC build for MPFR v2.4.2, GMP 4.3.2, and MPC 0.8.1.

If your VPS only has 768MB of memory, you will run out of memory in the next step. If you have 1GB of memory, you may be OK, but it can’t hurt to do this step. If you have 2GB of memory, or more, you can skip this step. This step adds 500MB of virtual memory, using a swap file.

Build GCC. This will run for hours. If this completes correctly, the last line you will see will say «success». It is normal to see some error-looking messages scrolling by quickly, as long as the build completes and echos «success». It’s always a good idea to build things in a different directory than a source directory. GCC documentation states that you should not use a build directory that is a sub-directory of the source directory.

If you set up a swap file in step 6, remove it. Without doing more configuring, after a reboot, it won’t be used as a swap file, and just take up hard drive space in your VPS.

Check the installed versions, and see their locations.

Add the new libraries to ld (the GNU linker).

Optionally make a hello world program.

Optionally reclaim hard drive space. Your

/sourceInstallations folder will be taking up around 8.0GB. It’s probably wise to keep the folders, as there are optional configuration options you may need to use at some point in the future, and it would be faster to have a lot already done. Also, the build process makes logs that you can later check and work from if something goes wrong. But, after running sudo make install earlier, your installed GCC isn’t depending on anything in this directory, and space can be at a premium, so you can do this step and reclaim the 8.0GB or so.

You now have your CentOS officially supported gcc and g++ still in /usr/bin/ , your CentOS officially supported 32-bit libs in /lib , your CentOS officially supported 64-bit libs in /lib64 , and your CentOS officially supported include files in /usr/include .

Your newer gcc and g++ are in /usr/local/bin , newer 32-bit libs in /usr/local/lib , your newer 64-bit libs in /usr/local/lib64 , and your newer include files in /usr/local/include .

источник

nix Craft

Linux and Unix tutorials for new and seasoned sysadmin

nix Craft

Linux and Unix tutorials for new and seasoned sysadmin

CentOS / RHEL 7: Install GCC (C and C++ Compiler) and Development Tools

Adblock detected 😱

CentOS / RHEL 7: Install GCC Package list

  1. autoconf
  2. automake
  3. binutils
  4. bison
  5. flex
  6. gcc (c compiler)
  7. gcc-c++ (c++ compiler)
  8. gettext
  9. libtool
  10. make
  11. patch
  12. pkgconfig
  13. redhat-rpm-config
  14. rpm-build
  15. rpm-sign

Installing GCC c and c++

Open the Terminal app and type the following commands.

Command to list groups on a CentOS / RHEL 7

Type the following yum command:
# yum group list
Sample outputs:
Fig. 01: CentOS / RHEL 7: List Package Groups Command
Another option:
# yum group list ids
Sample outputs:

Loaded plugins: fastestmirror There is no installed groups file. Maybe run: yum groups mark convert (see man yum) Loading mirror speeds from cached hostfile * base: centos.excellmedia.net * epel: mirror01.idc.hinet.net * extras: centos.excellmedia.net * updates: centos.excellmedia.net Available Environment Groups: Minimal Install (minimal) Compute Node (compute-node-environment) Infrastructure Server (infrastructure-server-environment) File and Print Server (file-print-server-environment) MATE Desktop (mate-desktop-environment) Basic Web Server (web-server-environment) Virtualization Host (virtualization-host-environment) Server with GUI (graphical-server-environment) GNOME Desktop (gnome-desktop-environment) KDE Plasma Workspaces (kde-desktop-environment) Development and Creative Workstation (developer-workstation-environment) Available Groups: CIFS file server (cifs-file-server) Compatibility Libraries (compat-libraries) Console Internet Tools (console-internet) Desktop (basic-desktop) Desktop Platform (desktop-platform) Desktop Platform Development (desktop-platform-devel) Development Tools (development) Eclipse (eclipse) Educational Software (education) Electronic Lab (electronic-lab) FCoE Storage Client (storage-client-fcoe) Fedora Packager (fedora-packager) General Purpose Desktop (general-desktop) Graphical Administration Tools (graphical-admin-tools) Haskell (haskell) Legacy UNIX Compatibility (legacy-unix) Messaging Client Support (system-management-messaging-client) Messaging Server Support (system-management-messaging-server) Milkymist (milkymist) MySQL Database client (mysql-client) MySQL Database server (mysql) NFS file server (nfs-file-server) Network Storage Server (storage-server) SNMP Support (system-management-snmp) Scientific Support (scientific) Security Tools (security-tools) Server Platform (server-platform) Server Platform Development (server-platform-devel) Smart Card Support (smart-card) Storage Availability Tools (storage-client-multipath) System Administration Tools (system-admin-tools) System Management (system-management) TeX support (tex) TurboGears application framework (turbogears) Virtualization (virtualization) Web-Based Enterprise Management (system-management-wbem) Xfce (xfce-desktop) iSCSI Storage Client (storage-client-iscsi) Done

Command to install GCC and Development Tools on a CentOS / RHEL 7 server

Type the following yum command as root user:
# yum group install «Development Tools»
OR
$ sudo yum group install «Development Tools»
If above command failed, try:
# yum groupinstall «Development Tools»
Sample outputs:

Animated gif 01: Installing C & C++ and related packages on a CentOS and RHEL 7

A note about failing groupinstall on CentOS/RHEL 7.x

To install all the packages belonging to a package group called “Development Tools” use the following command:
# yum —setopt=group_package_types=mandatory,default,optional groupinstall «Development Tools»
OR
# yum —setopt=group_package_types=mandatory,default,optional group install «Development Tools»
The yum has changed in Red Hat Enterprise Linux 7/CentOS 7. The package group “Development Tools”” has only the optional packages which by default doesn’t get installed. So we will need to pass the option —setopt=group_package_types=mandatory,default,optional to install the optional packages too.

Verify your gcc installation on a CentOS / RHEL 7 server

Type the following command to see gcc location:

Type the following command to see gcc compiler version:

Test gcc C compiler with a sample foo.c program

Create a file called foo.c as follows:

To compile foo.c into foo executable file, type:
$ cc foo.c -o foo
To execute foo program, type:

A note about install man pages on a CentOS 6/7

Use the yum command as follows:
$ ## [ CentOS 7 ] ##
$ sudo yum install man-pages man-db man
$ ## [ CentOS 6.x ] ##
$ sudo yum install man man-pages

Conclusion

You learned how to install GNU c, c++ compilers and releated tools on a CentOS or Red Hat Enterprise Linux version 7.x. See GCC site for more info.

Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.

Related Tutorials

Your support makes a big difference:

I have a small favor to ask. More people are reading the nixCraft. Many of you block advertising which is your right, and advertising revenues are not sufficient to cover my operating costs. So you can see why I need to ask for your help. The nixCraft takes a lot of my time and hard work to produce. If everyone who reads nixCraft, who likes it, helps fund it, my future would be more secure. You can donate as little as $1 to support nixCraft:

Join the discussion at www.nixcraft.com

18 comment

It will install all gcc software and upgrade all the files to satisfy dependices

We should have no space between group and install.
# yum groupinstall «Development Tools»

Please, fix ‘group install‘ -> ‘groupinstall‘.
For example:
yum groupinstall «Development Tools»

yum group install «Development Tools»
right is
yum groupinstall «Development Tools»

hello, i have a Problem with gcc, when i need
when I run include command I get the following message:
bash: syntax error near unexpected token `newline ‘

#yum install “development tools” is not working in centos 7

Use groupinstall as the article says…

for centos/rhel 7 use (missing the “s” off groups):
yum groups install «Development Tools»

Durring install if you get any errors regarding kernel packages ex:

All kernel packages are on the yum exclude list so you may need to do the following:
yum -y install kernel-devel —disableexcludes=all

to see all groups available:
yum groups list

In Centos 7:
Warning: Group development does not have any packages to install.

Put quotes around the “Development Tools” group name, as per the article (copy and paste is your friend)!

I really appreciate your help

on CentOS 7 you can try this( It is one line !!) :
yum groupinstall «Development Tools» —setopt=group_package_types=mandatory,default,optional

this is a yum setup.
Have a nice day,
AlucarD

@AlucarD’s way is definitely works

so, how do i became root? it says i have to be root to perform this action

Good evening.
Hint from AlucarD saved my day:
yum groupinstall «Development Tools» —setopt=group_package_types=mandatory,default,optional
Now, my Server is optimal.

Wow this is great for automating installs, thanks for the info!

источник

Читайте также:  Установка бушвакеров уаз патриот

Добавить комментарий

Adblock
detector