Build x86 64 linux gnu

Building GCC 10 on Ubuntu Linux

This is a short article about compiling GCC 10.1 from sources on Ubuntu 20.04 64 bits. The default version of GCC on Ubuntu 20.04 is 9.3 which is not bad, however version 10 has complete C++11, C++14, C++17 support and partial C++20 support. GCC 10 has C11 and C++14 support enabled by default, no need to add -std=c11 or -std=c++14.

First, let’s make sure that we have an up to date system:

 1 sudo apt update 2 sudo apt upgrade

Now, install the default GCC toolchain and a few extra utilities with:

 1 sudo apt install build-essential wget m4 flex bison

Next, we’ll download the GCC 10 source and his prerequisites from http://gcc.gnu.org/mirrors.html:

 1 cd ~ 2 wget https://ftpmirror.gnu.org/gcc/gcc-10.1.0/gcc-10.1.0.tar.xz 3 tar xf gcc-10.1.0.tar.xz 4 cd gcc-10.1.0 5 contrib/download_prerequisites

At this point, we can configure the build. In order to keep the system clean, we will use /usr/local/gcc-10.1.0 for the installation folder and append the suffix -10.1 to the GCC compilers. You typically don’t want to mess the system’s default GCC because other packages may depend on the default version.

 1 cd ~ 2 mkdir build && cd build 3 ../gcc-10.1.0/configure -v --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu --prefix=/usr/local/gcc-10.1.0 --enable-checking=release --enable-languages=c,c++,fortran --disable-multilib --program-suffix=-10.1

Now, we are ready to build GCC, you typically want to pass twice the number of your computer cores to the make command in order to speed up the build. I have a quad-core system, so I will use 8 parallel jobs to build GCC:

Depending on the speed of your computer the build phase could take from about 30 minutes to a few hours.

Once the above phase is finished, you can install the built GCC with:

If you want to permanently add the compilers to your system’s path, add the next two lines at the end of your .bashrc file:

 1 export export PATH=/usr/local/gcc-10.1.0/bin:$PATH 2 export LD_LIBRARY_PATH=/usr/local/gcc-10.1.0/lib64:$LD_LIBRARY_PATH

Don’t know how to open .bashrc ? No problem, you can find it from your Terminal:

Paste at the end .bashrc the above export lines, save the file and close gedit. Now, you just need to instruct Bash to reload .bashrc (this is automatically done when you restart your machine):

Читайте также:  Какие оболочки линукс бывают

Time to test our shiny new compilers. Open your favorite text editor and copy the next piece of code (I assume you’ll save the file as test_lambda.cpp):

 1 // C++14 generalized lambda (could use "auto" for the type of a parameter) 2 #include 3 4 int main()  5 std::cout  <[](auto a, auto b)  return a + b; > (5, 6)  <std::endl; 6 std::cout  <[](auto a, auto b)  return a + b; > (5.23, 6.45)  <std::endl; 7 return 0; 8 >

The code uses a generalized lambda (we could use auto for the type of the parameters), this was introduced in the C++14 standard. We can compile and test the above program with:

 1 g++-10.1 -Wall -pedantic test_lambda.cpp -o test_lambda 2 ./test_lambda 3 11 4 11.68

As mentioned at the beginning of this article, GCC 10.1 has complete support for C++17. Let’s test an example of using C++17 modification to static_assert:

  1 #include  2 #include  3 4 struct A   5 int foo; 6 >; 7 8 struct B   9 int foo = 0; 10 >; 11 12 template typename T> 13 void print(const T& a) 14 static_assert(std::is_podT>::value); 15 std::cout  <a.foo  <'\n'; 16 > 17 18 int main()  19 A x1>; 20 B y2>; 21 B z; 22 23 printA>(x); 24 printB>(y); 25 printB>(z); 26 27 return 0; 28 >

You can compile the above code if you pass std=c++17 to the compiler and you should get a compiler error triggered by lines 14 and 20 from the above code

 1 g++-10.1 -std=c++17 -Wall -pedantic test_assert.cpp -o test_assert 2 test_assert.cpp: In instantiation of ‘void print(const T&) [with T = B]’: 3 test_assert.cpp:24:13: required from here 4 test_assert.cpp:14:33: error: static assertion failed 5 14 | static_assert(std::is_pod::value); 6 | ^~~~~

If you are a Fortran programmer, you can use some of the Fortran 2008 features like do concurrent with gfortran-10.1:

  1 integer,parameter::mm=100000 2 real::a(mm), b(mm) 3 real::fact=0.5 4 5 ! initialize the arrays 6 ! . 7 8 do concurrent (i = 1 : mm) 9 a(i) = a(i) + b(i) 10 enddo 11 12 end

The above code can be compiled with (supposing you’ve named it test_concurrent_do.f90s):

 1 gfortran-10.1 test_concurrent_do.f90 -o test_concurrent_do 2 ./test_concurrent_do

If you are interested in learning more about the new C++11 syntax I would recommend reading The C++ Programming Language by Bjarne Stroustrup.

or, Professional C++ by M. Gregoire, N. A. Solter, S. J. Kleper 4th edition:

If you need to brush your Fortran knowledge a good book is Modern Fortran Explained by M. Metcalf, J. Reid and M. Cohen:

Disclaimer:
All data and information provided on this site is for informational purposes only. solarianprogrammer.com makes no representations as to accuracy, completeness, currentness, suitability, or validity of any information on this site and will not be liable for any errors, omissions, or delays in this information or any losses, injuries, or damages arising from its display or use. All information is provided on an as-is basis. solarianprogrammer.com does not collect any personal information about its visitors except that which they provide voluntarily when leaving comments. This information will never be disclosed to any third party for any purpose. Some of the links contained within this site have my referral id, which provides me with a small commission for each sale. Thank you for understanding.

Copyright © 2023 — Paul Silisteanu

Источник

gcc⚓︎

Пакет содержит набор компиляторов GNU для таких языков как Си и Си++.

Версия: 11.2.0

Размер: 77.14Mb

Приоритет: Необходимый

MD5: 31c86f2ced76acac66992eeedce2fce2

SBU (Сборка временной системы): 14.8

Подготовка⚓︎

Исправьте пути установки библиотек:

 sed -e '/m64=/s/lib64/lib/' \ -e '/m32=/s/m32=.*/m32=..\/lib32$(call if_multiarch,:i386-linux-gnu)/' \ -i.orig gcc/config/i386/t-linux64 

Настройка⚓︎

На данном этапе необходимы только компиляторы для C и C++, однако вы можете собрать компиляторы для любых поддерживаемых GCC языков программирования, перечислив их через запятые в опции configure —enable-languages=c,c++ . GCC поддерживает следующие языки — c,c++,d,fortran,go,objc,obj-c++ . вы можете собрать все доступные компиляторы, добавив параметр —enable-languages=c,c++,d,fortran,go,objc,obj-c++ . Если позднее вам потребуется компилятор для какого либо языка из этого списка — пересоберите GCC с его поддержкой.

 mkdir -v build cd build ../configure --prefix=/usr \ LD=ld \ --disable-bootstrap \ --with-system-zlib \ --enable-languages=c,c++ --disable-multilib 

Для multilib⚓︎

 mkdir -v build cd build ../configure --prefix=/usr \ LD=ld \ --disable-bootstrap \ --with-system-zlib \ --enable-languages=c,c++ --enable-multilib --with-multilib-list=m64,m32 

Значения параметров⚓︎

—disable-bootstrap — предотвращает многократную пересборку GCC

LD=ld — сообщает GCC использовать ранее установленную версию компоновщика

Сборка⚓︎

Тестирование⚓︎

  • Увеличьте размер стека по умолчанию
  • Произведите тестирование от непривилегированного пользователя во избежание непредвиденных ситуаций с системой.
 ulimit -s 32768 chown -Rv tester . su tester -c "PATH=$PATH make -k check" 

Тестирование этого пакета занимает достаточно много времени.

Для просмотра итогов теста выполните:

Известно, что 6 тестов, связанных с get_time , дают сбои. По видимому, это связано с локалью en_HK . Кроме того, тест COSTEXPR-52830 не удается.

Установка⚓︎

  • Удалите ненужную директорию,
  • Убедитесь, что владелец установленных заголовков корректный,
  • По историческим причинам некоторые программы могут пытаться найти cpp в директории /lib . Создайте ссылку,
  • Для поддержки LTO требуется следующая символическая ссылка,
  • Переместите файлы в правильное место:
 rm -rf /usr/lib/gcc/$(gcc -dumpmachine)/11.2.0/include-fixed/bits/ chown -v -R root:root \ /usr/lib/gcc/*linux-gnu/11.2.0/include,-fixed> ln -svr /usr/bin/cpp /usr/lib ln -sfv ../../libexec/gcc/$(gcc -dumpmachine)/11.2.0/liblto_plugin.so \ /usr/lib/bfd-plugins/ mkdir -pv /usr/share/gdb/auto-load/usr/lib,32> mv -v /usr/lib/*gdb.py /usr/share/gdb/auto-load/usr/lib mv -v /usr/lib32/*gdb.py /usr/share/gdb/auto-load/usr/lib32 

При использовании раздельных каталогов:⚓︎

Проверка работоспособности⚓︎

Сейчас необходимо проверить работу gcc . Если всё нормально, то продолжайте сборку.

 echo 'int main()<>' > dummy.c cc dummy.c -v -Wl,--verbose &> dummy.log readelf -l a.out | grep ': /lib' 

Ошибок быть не должно, а результат команды (учитывая различия в имени динамического компоновщика, зависящие от платформы) будет следующий:

 Requesting program interpreter: /lib64/ld-linux-x86-64.so.2] 

Проверим что задействованы правильные стартовые файлы. Выполните команду:

 grep -o '/usr/lib.*/crt[1in].*succeeded' dummy.log 
 /usr/lib/gcc/x86_64-pc-linux-gnu/11.2.0/../../../../lib/crt1.o succeeded /usr/lib/gcc/x86_64-pc-linux-gnu/11.2.0/../../../../lib/crti.o succeeded /usr/lib/gcc/x86_64-pc-linux-gnu/11.2.0/../../../../lib/crtn.o succeeded 

В зависимости от архитектуры, приведенное выше может немного отличаться. Разница будет в названии каталога после /usr/lib/gcc . Здесь важно обратить внимание на то, что gcc обнаружил все три файла crt * .o в каталоге /usr/lib .

Проверим то, что компилятор выполняет поиск корректных заголовочных файлов:

 grep -B4 '^ /usr/include' dummy.log 
 #include search starts here: /usr/lib/gcc/x86_64-pc-linux-gnu/11.2.0/include /usr/local/include /usr/lib/gcc/x86_64-pc-linux-gnu/11.2.0/include-fixed 

Проверим, что компоновщик использует корректные пути поиска:

 grep 'SEARCH.*/usr/lib' dummy.log |sed 's|; |\n|g' 
 SEARCH_DIR("/usr/x86_64-pc-linux-gnu/lib64") SEARCH_DIR("/usr/local/lib64") SEARCH_DIR("/lib64") SEARCH_DIR("/usr/lib64") SEARCH_DIR("/usr/x86_64-pc-linux-gnu/lib") SEARCH_DIR("/usr/local/lib") SEARCH_DIR("/lib") SEARCH_DIR("/usr/lib"); 

Проверим, что используется корректная стандартная библиотека

 grep "/lib.*/libc.so.6 " dummy.log 
 attempt to open /usr/lib/libc.so.6 succeeded 

Проверим, что используется корректный динамический компоновщик:

 grep "found ld-linux*" dummy.log 

Результат выполнения должен быть (учитывая различия в имени динамического компоновщика, зависящие от платформы):

 found ld-linux-x86-64.so.2 at /usr/lib/ld-linux-x86-64.so.2 

Если вывод не соответствует вышеуказанному, или вообще не получен, значит, что-то не так. Изучите и повторите шаги, чтобы выяснить, в чем проблема. Перед продолжением процесса необходимо решить любые проблемы.

 rm -v dummy.c a.out dummy.log 

Установленные файлы⚓︎

Программы: c++ (ссылка на g++), cc (ссылка на gcc), cpp, g++, gcc, gcc-ar, gcc-nm, gcc-ranlib, gcov, gcov-dump и gcov-tool

Библиотеки: libasan., libatomic., libcc1.so, libgcc.a, libgcc_eh.a, libgcc_s.so, libgcov.a, libgomp., libitm., liblsan., liblto_plugin.so, libquadmath., libssp., libssp_nonshared.a, libstdc++., libstdc++fs.a, libsupc++.a, libtsan. и libubsan.

Директории: /usr/include/c++, /usr/lib/gcc, /usr/libexec/gcc и /usr/share/gcc-11.2.0

Источник

Оцените статью
Adblock
detector