Пакет: binutils
- Версия
- 2.44
- Релиз
- 1.niceos5
- Архитектура
- x86_64
- Хэш GOST
- 28c0f559cceadeb80f12bd7c71ddb3218bc772f211a32a19dbfff5fdc4bff756
- Хэш MD5
- 2e9a54cad7af0163ab2856c8931c6f72
- Хэш SHA256
- e5992efd4baf3b3f51f4f44d326eccd847a1c210bef2cd9c7302d74380d3f280
- Лицензия
- GPLv2+
- Дата сборки
- 12 мая 2025 г.
- Размер
- 21,374 ГиБ
- Совместимые ОС
- rpm файл:
- binutils-2.44-1.niceos5.x86_64.rpm
Подпакеты
| Имя | Краткое описание |
|---|---|
| binutils-libs | Описание отсутствует |
| binutils-devel | Описание отсутствует |
Зависимости
| Имя | Тип | Версия |
|---|---|---|
| /usr/bin/env | runtime | - |
| binutils-libs | runtime | - |
| libbfd-2.44.so()(64bit) | runtime | - |
| libc.so.6()(64bit) | runtime | - |
| libc.so.6(GLIBC_2.11)(64bit) | runtime | - |
| libc.so.6(GLIBC_2.14)(64bit) | runtime | - |
| libc.so.6(GLIBC_2.15)(64bit) | runtime | - |
| libc.so.6(GLIBC_2.2.5)(64bit) | runtime | - |
| libc.so.6(GLIBC_2.27)(64bit) | runtime | - |
| libc.so.6(GLIBC_2.3)(64bit) | runtime | - |
| libc.so.6(GLIBC_2.3.4)(64bit) | runtime | - |
| libc.so.6(GLIBC_2.33)(64bit) | runtime | - |
| libc.so.6(GLIBC_2.34)(64bit) | runtime | - |
| libc.so.6(GLIBC_2.38)(64bit) | runtime | - |
| libc.so.6(GLIBC_2.4)(64bit) | runtime | - |
| libc.so.6(GLIBC_2.6)(64bit) | runtime | - |
| libctf-nobfd.so.0()(64bit) | runtime | - |
| libctf-nobfd.so.0(LIBCTF_1.0)(64bit) | runtime | - |
| libctf-nobfd.so.0(LIBCTF_1.1)(64bit) | runtime | - |
| libctf.so.0()(64bit) | runtime | - |
| libctf.so.0(LIBCTF_1.0)(64bit) | runtime | - |
| libctf.so.0(LIBCTF_1.1)(64bit) | runtime | - |
| libdebuginfod.so.1()(64bit) | runtime | - |
| libdebuginfod.so.1(ELFUTILS_0.178)(64bit) | runtime | - |
| libfl.so.2()(64bit) | runtime | - |
| libgcc_s.so.1()(64bit) | runtime | - |
| libgcc_s.so.1(GCC_3.0)(64bit) | runtime | - |
| libgprofng.so.0()(64bit) | runtime | - |
| libm.so.6()(64bit) | runtime | - |
| libopcodes-2.44.so()(64bit) | runtime | - |
| libsframe.so.1()(64bit) | runtime | - |
| libsframe.so.1(LIBSFRAME_1.0)(64bit) | runtime | - |
| libstdc++.so.6()(64bit) | runtime | - |
| libstdc++.so.6(CXXABI_1.3)(64bit) | runtime | - |
| libstdc++.so.6(CXXABI_1.3.8)(64bit) | runtime | - |
| libstdc++.so.6(CXXABI_1.3.9)(64bit) | runtime | - |
| libstdc++.so.6(GLIBCXX_3.4)(64bit) | runtime | - |
| libstdc++.so.6(GLIBCXX_3.4.32)(64bit) | runtime | - |
| libz.so.1()(64bit) | runtime | - |
| libzstd.so.1()(64bit) | runtime | - |
| perl(Cwd) | runtime | - |
| perl(File::Basename) | runtime | - |
| perl(File::stat) | runtime | - |
| perl(Getopt::Long) | runtime | - |
| perl(List::Util) | runtime | - |
| perl(POSIX) | runtime | - |
| perl(bigint) | runtime | - |
| perl(feature) | runtime | - |
| perl(strict) | runtime | - |
| perl(warnings) | runtime | - |
| rtld(GNU_HASH) | runtime | - |
Граф зависимостей
История изменений
| Дата | Автор | Сообщение |
|---|---|---|
| 31 мар. 2025 г. | Stanislav Belikov <sbelikov@ncsgp.ru> | Первая сборка для binutils |
Файлы пакета
-
- /etc/gprofng.rc 3,893 КиБ
-
-
-
- /usr/bin/addr2line 37,859 КиБ
- /usr/bin/ar 79,273 КиБ
- /usr/bin/as 886,57 КиБ
- /usr/bin/c++filt 36,281 КиБ
- /usr/bin/elfedit 49,148 КиБ
- /usr/bin/gp-archive 15 Б
- /usr/bin/gp-collect-app 19 Б
- /usr/bin/gp-display-html 20 Б
- /usr/bin/gp-display-src 19 Б
- /usr/bin/gp-display-text 20 Б
- /usr/bin/gprof 111,367 КиБ
- /usr/bin/gprofng 25,734 КиБ
- /usr/bin/gprofng-archive 53,523 КиБ
- /usr/bin/gprofng-collect-app 64,969 КиБ
- /usr/bin/gprofng-display-html 630,354 КиБ
- /usr/bin/gprofng-display-src 36,516 КиБ
- /usr/bin/gprofng-display-text 198,531 КиБ
- /usr/bin/ld 1,362 МиБ
- /usr/bin/ld.bfd 1,362 МиБ
- /usr/bin/nm 65,773 КиБ
- /usr/bin/objcopy 213,289 КиБ
- /usr/bin/objdump 493,578 КиБ
- /usr/bin/ranlib 79,305 КиБ
- /usr/bin/readelf 866,125 КиБ
- /usr/bin/size 41,641 КиБ
- /usr/bin/strings 45,617 КиБ
- /usr/bin/strip 213,297 КиБ
-
-
-
- /usr/lib/ldscripts/elf32_x86_64.x 10,703 КиБ
- /usr/lib/ldscripts/elf32_x86_64.xbn 10,511 КиБ
- /usr/lib/ldscripts/elf32_x86_64.xc 10,357 КиБ
- /usr/lib/ldscripts/elf32_x86_64.xce 10,695 КиБ
- /usr/lib/ldscripts/elf32_x86_64.xcer 10,639 КиБ
- /usr/lib/ldscripts/elf32_x86_64.xd 10,572 КиБ
- /usr/lib/ldscripts/elf32_x86_64.xdc 10,261 КиБ
- /usr/lib/ldscripts/elf32_x86_64.xdce 10,599 КиБ
- /usr/lib/ldscripts/elf32_x86_64.xdcer 10,542 КиБ
- /usr/lib/ldscripts/elf32_x86_64.xde 10,91 КиБ
- /usr/lib/ldscripts/elf32_x86_64.xder 10,854 КиБ
- /usr/lib/ldscripts/elf32_x86_64.xdw 10,223 КиБ
- /usr/lib/ldscripts/elf32_x86_64.xdwe 10,561 КиБ
- /usr/lib/ldscripts/elf32_x86_64.xdwer 10,504 КиБ
- /usr/lib/ldscripts/elf32_x86_64.xe 11,007 КиБ
- /usr/lib/ldscripts/elf32_x86_64.xer 10,95 КиБ
- /usr/lib/ldscripts/elf32_x86_64.xn 10,672 КиБ
- /usr/lib/ldscripts/elf32_x86_64.xr 6,498 КиБ
- /usr/lib/ldscripts/elf32_x86_64.xs 10,201 КиБ
- /usr/lib/ldscripts/elf32_x86_64.xsc 9,89 КиБ
- /usr/lib/ldscripts/elf32_x86_64.xsce 10,228 КиБ
- /usr/lib/ldscripts/elf32_x86_64.xscer 10,171 КиБ
- /usr/lib/ldscripts/elf32_x86_64.xse 10,539 КиБ
- /usr/lib/ldscripts/elf32_x86_64.xser 10,482 КиБ
- /usr/lib/ldscripts/elf32_x86_64.xsw 9,852 КиБ
- /usr/lib/ldscripts/elf32_x86_64.xswe 10,189 КиБ
- /usr/lib/ldscripts/elf32_x86_64.xswer 10,133 КиБ
- /usr/lib/ldscripts/elf32_x86_64.xu 6,521 КиБ
- /usr/lib/ldscripts/elf32_x86_64.xw 10,319 КиБ
- /usr/lib/ldscripts/elf32_x86_64.xwe 10,657 КиБ
- /usr/lib/ldscripts/elf32_x86_64.xwer 10,601 КиБ
- /usr/lib/ldscripts/elf_i386.x 10,074 КиБ
- /usr/lib/ldscripts/elf_i386.xbn 9,882 КиБ
- /usr/lib/ldscripts/elf_i386.xc 9,859 КиБ
- /usr/lib/ldscripts/elf_i386.xce 10,197 КиБ
- /usr/lib/ldscripts/elf_i386.xcer 10,141 КиБ
- /usr/lib/ldscripts/elf_i386.xd 9,941 КиБ
- /usr/lib/ldscripts/elf_i386.xdc 9,761 КиБ
- /usr/lib/ldscripts/elf_i386.xdce 10,099 КиБ
- /usr/lib/ldscripts/elf_i386.xdcer 10,042 КиБ
- /usr/lib/ldscripts/elf_i386.xde 10,279 КиБ
- /usr/lib/ldscripts/elf_i386.xder 10,223 КиБ
- /usr/lib/ldscripts/elf_i386.xdw 9,723 КиБ
- /usr/lib/ldscripts/elf_i386.xdwe 10,061 КиБ
- /usr/lib/ldscripts/elf_i386.xdwer 10,004 КиБ
- /usr/lib/ldscripts/elf_i386.xe 10,378 КиБ
- /usr/lib/ldscripts/elf_i386.xer 10,321 КиБ
- /usr/lib/ldscripts/elf_i386.xn 10,043 КиБ
- /usr/lib/ldscripts/elf_i386.xr 6,239 КиБ
- /usr/lib/ldscripts/elf_i386.xs 9,57 КиБ
- /usr/lib/ldscripts/elf_i386.xsc 9,39 КиБ
- /usr/lib/ldscripts/elf_i386.xsce 9,728 КиБ
- /usr/lib/ldscripts/elf_i386.xscer 9,671 КиБ
- /usr/lib/ldscripts/elf_i386.xse 9,908 КиБ
- /usr/lib/ldscripts/elf_i386.xser 9,852 КиБ
- /usr/lib/ldscripts/elf_i386.xsw 9,352 КиБ
- /usr/lib/ldscripts/elf_i386.xswe 9,689 КиБ
- /usr/lib/ldscripts/elf_i386.xswer 9,633 КиБ
- /usr/lib/ldscripts/elf_i386.xu 6,263 КиБ
- /usr/lib/ldscripts/elf_i386.xw 9,821 КиБ
- /usr/lib/ldscripts/elf_i386.xwe 10,159 КиБ
- /usr/lib/ldscripts/elf_i386.xwer 10,103 КиБ
- /usr/lib/ldscripts/elf_iamcu.x 9,771 КиБ
- /usr/lib/ldscripts/elf_iamcu.xbn 9,578 КиБ
- /usr/lib/ldscripts/elf_iamcu.xc 9,556 КиБ
- /usr/lib/ldscripts/elf_iamcu.xce 9,894 КиБ
- /usr/lib/ldscripts/elf_iamcu.xcer 9,837 КиБ
- /usr/lib/ldscripts/elf_iamcu.xd 9,638 КиБ
- /usr/lib/ldscripts/elf_iamcu.xdc 9,457 КиБ
- /usr/lib/ldscripts/elf_iamcu.xdce 9,795 КиБ
- /usr/lib/ldscripts/elf_iamcu.xdcer 9,738 КиБ
- /usr/lib/ldscripts/elf_iamcu.xde 9,976 КиБ
- /usr/lib/ldscripts/elf_iamcu.xder 9,919 КиБ
- /usr/lib/ldscripts/elf_iamcu.xdw 9,419 КиБ
- /usr/lib/ldscripts/elf_iamcu.xdwe 9,757 КиБ
- /usr/lib/ldscripts/elf_iamcu.xdwer 9,7 КиБ
- /usr/lib/ldscripts/elf_iamcu.xe 10,074 КиБ
- /usr/lib/ldscripts/elf_iamcu.xer 10,018 КиБ
- /usr/lib/ldscripts/elf_iamcu.xn 9,739 КиБ
- /usr/lib/ldscripts/elf_iamcu.xr 6,18 КиБ
- /usr/lib/ldscripts/elf_iamcu.xs 9,267 КиБ
- /usr/lib/ldscripts/elf_iamcu.xsc 9,086 КиБ
- /usr/lib/ldscripts/elf_iamcu.xsce 9,424 КиБ
- /usr/lib/ldscripts/elf_iamcu.xscer 9,367 КиБ
- /usr/lib/ldscripts/elf_iamcu.xse 9,604 КиБ
- /usr/lib/ldscripts/elf_iamcu.xser 9,548 КиБ
- /usr/lib/ldscripts/elf_iamcu.xsw 9,048 КиБ
- /usr/lib/ldscripts/elf_iamcu.xswe 9,386 КиБ
- /usr/lib/ldscripts/elf_iamcu.xswer 9,329 КиБ
- /usr/lib/ldscripts/elf_iamcu.xu 6,203 КиБ
- /usr/lib/ldscripts/elf_iamcu.xw 9,518 КиБ
- /usr/lib/ldscripts/elf_iamcu.xwe 9,855 КиБ
- /usr/lib/ldscripts/elf_iamcu.xwer 9,799 КиБ
- /usr/lib/ldscripts/elf_x86_64.x 10,699 КиБ
- /usr/lib/ldscripts/elf_x86_64.xbn 10,507 КиБ
- /usr/lib/ldscripts/elf_x86_64.xc 10,354 КиБ
- /usr/lib/ldscripts/elf_x86_64.xce 10,691 КиБ
- /usr/lib/ldscripts/elf_x86_64.xcer 10,635 КиБ
- /usr/lib/ldscripts/elf_x86_64.xd 10,568 КиБ
- /usr/lib/ldscripts/elf_x86_64.xdc 10,257 КиБ
- /usr/lib/ldscripts/elf_x86_64.xdce 10,595 КиБ
- /usr/lib/ldscripts/elf_x86_64.xdcer 10,538 КиБ
- /usr/lib/ldscripts/elf_x86_64.xde 10,906 КиБ
- /usr/lib/ldscripts/elf_x86_64.xder 10,85 КиБ
- /usr/lib/ldscripts/elf_x86_64.xdw 10,219 КиБ
- /usr/lib/ldscripts/elf_x86_64.xdwe 10,557 КиБ
- /usr/lib/ldscripts/elf_x86_64.xdwer 10,5 КиБ
- /usr/lib/ldscripts/elf_x86_64.xe 11,003 КиБ
- /usr/lib/ldscripts/elf_x86_64.xer 10,946 КиБ
- /usr/lib/ldscripts/elf_x86_64.xn 10,668 КиБ
- /usr/lib/ldscripts/elf_x86_64.xr 6,498 КиБ
- /usr/lib/ldscripts/elf_x86_64.xs 10,197 КиБ
- /usr/lib/ldscripts/elf_x86_64.xsc 9,886 КиБ
- /usr/lib/ldscripts/elf_x86_64.xsce 10,224 КиБ
- /usr/lib/ldscripts/elf_x86_64.xscer 10,167 КиБ
- /usr/lib/ldscripts/elf_x86_64.xse 10,535 КиБ
- /usr/lib/ldscripts/elf_x86_64.xser 10,479 КиБ
- /usr/lib/ldscripts/elf_x86_64.xsw 9,848 КиБ
- /usr/lib/ldscripts/elf_x86_64.xswe 10,186 КиБ
- /usr/lib/ldscripts/elf_x86_64.xswer 10,129 КиБ
- /usr/lib/ldscripts/elf_x86_64.xu 6,521 КиБ
- /usr/lib/ldscripts/elf_x86_64.xw 10,315 КиБ
- /usr/lib/ldscripts/elf_x86_64.xwe 10,653 КиБ
- /usr/lib/ldscripts/elf_x86_64.xwer 10,597 КиБ
- /usr/lib/ldscripts/stamp 0 Б
-
-
-
-
-
-
- /usr/share/locale/bg/LC_MESSAGES/binutils.mo 158,188 КиБ
- /usr/share/locale/bg/LC_MESSAGES/gprof.mo 12,755 КиБ
- /usr/share/locale/bg/LC_MESSAGES/ld.mo 106,161 КиБ
-
-
-
-
- /usr/share/locale/ca/LC_MESSAGES/binutils.mo 151,625 КиБ
-
-
-
-
- /usr/share/locale/da/LC_MESSAGES/bfd.mo 150,042 КиБ
- /usr/share/locale/da/LC_MESSAGES/binutils.mo 68,383 КиБ
- /usr/share/locale/da/LC_MESSAGES/gprof.mo 10,233 КиБ
- /usr/share/locale/da/LC_MESSAGES/ld.mo 40,662 КиБ
- /usr/share/locale/da/LC_MESSAGES/opcodes.mo 17,18 КиБ
-
-
-
-
- /usr/share/locale/de/LC_MESSAGES/gprof.mo 10,588 КиБ
- /usr/share/locale/de/LC_MESSAGES/ld.mo 50,673 КиБ
- /usr/share/locale/de/LC_MESSAGES/opcodes.mo 54,588 КиБ
-
-
-
-
- /usr/share/locale/eo/LC_MESSAGES/gprof.mo 10,5 КиБ
-
-
-
-
- /usr/share/locale/es/LC_MESSAGES/bfd.mo 234,267 КиБ
- /usr/share/locale/es/LC_MESSAGES/binutils.mo 118,151 КиБ
- /usr/share/locale/es/LC_MESSAGES/gas.mo 499,732 КиБ
- /usr/share/locale/es/LC_MESSAGES/gprof.mo 10,884 КиБ
- /usr/share/locale/es/LC_MESSAGES/ld.mo 136,346 КиБ
- /usr/share/locale/es/LC_MESSAGES/opcodes.mo 38,974 КиБ
-
-
-
-
- /usr/share/locale/fi/LC_MESSAGES/bfd.mo 158,9 КиБ
- /usr/share/locale/fi/LC_MESSAGES/binutils.mo 206,126 КиБ
- /usr/share/locale/fi/LC_MESSAGES/gas.mo 432,427 КиБ
- /usr/share/locale/fi/LC_MESSAGES/gprof.mo 10,87 КиБ
- /usr/share/locale/fi/LC_MESSAGES/ld.mo 36,572 КиБ
- /usr/share/locale/fi/LC_MESSAGES/opcodes.mo 30,528 КиБ
-
-
-
-
- /usr/share/locale/fr/LC_MESSAGES/bfd.mo 244,874 КиБ
- /usr/share/locale/fr/LC_MESSAGES/binutils.mo 335,121 КиБ
- /usr/share/locale/fr/LC_MESSAGES/gas.mo 586,724 КиБ
- /usr/share/locale/fr/LC_MESSAGES/gprof.mo 11,161 КиБ
- /usr/share/locale/fr/LC_MESSAGES/ld.mo 186,056 КиБ
- /usr/share/locale/fr/LC_MESSAGES/opcodes.mo 55,866 КиБ
-
-
-
-
- /usr/share/locale/ga/LC_MESSAGES/gprof.mo 10,258 КиБ
- /usr/share/locale/ga/LC_MESSAGES/ld.mo 58,245 КиБ
- /usr/share/locale/ga/LC_MESSAGES/opcodes.mo 30,021 КиБ
-
-
-
-
- /usr/share/locale/hr/LC_MESSAGES/bfd.mo 5,063 КиБ
- /usr/share/locale/hr/LC_MESSAGES/binutils.mo 21,106 КиБ
-
-
-
-
- /usr/share/locale/hu/LC_MESSAGES/gprof.mo 10,949 КиБ
-
-
-
-
- /usr/share/locale/id/LC_MESSAGES/bfd.mo 140,896 КиБ
- /usr/share/locale/id/LC_MESSAGES/binutils.mo 149,626 КиБ
- /usr/share/locale/id/LC_MESSAGES/gas.mo 408,378 КиБ
- /usr/share/locale/id/LC_MESSAGES/gprof.mo 10,281 КиБ
- /usr/share/locale/id/LC_MESSAGES/ld.mo 54,536 КиБ
- /usr/share/locale/id/LC_MESSAGES/opcodes.mo 29,603 КиБ
-
-
-
-
- /usr/share/locale/it/LC_MESSAGES/binutils.mo 188,272 КиБ
- /usr/share/locale/it/LC_MESSAGES/gprof.mo 10,503 КиБ
- /usr/share/locale/it/LC_MESSAGES/ld.mo 56,69 КиБ
- /usr/share/locale/it/LC_MESSAGES/opcodes.mo 25,771 КиБ
-
-
-
-
- /usr/share/locale/ja/LC_MESSAGES/bfd.mo 131,53 КиБ
- /usr/share/locale/ja/LC_MESSAGES/binutils.mo 146,604 КиБ
- /usr/share/locale/ja/LC_MESSAGES/gas.mo 36,333 КиБ
- /usr/share/locale/ja/LC_MESSAGES/gprof.mo 2,996 КиБ
- /usr/share/locale/ja/LC_MESSAGES/ld.mo 62,591 КиБ
-
-
-
-
- /usr/share/locale/ka/LC_MESSAGES/bfd.mo 4,916 КиБ
- /usr/share/locale/ka/LC_MESSAGES/gprof.mo 15,11 КиБ
- /usr/share/locale/ka/LC_MESSAGES/ld.mo 31,435 КиБ
-
-
-
-
- /usr/share/locale/ms/LC_MESSAGES/bfd.mo 1,82 КиБ
- /usr/share/locale/ms/LC_MESSAGES/gprof.mo 10,481 КиБ
-
-
-
-
- /usr/share/locale/nl/LC_MESSAGES/gprof.mo 10,523 КиБ
- /usr/share/locale/nl/LC_MESSAGES/opcodes.mo 24,707 КиБ
-
-
-
-
- /usr/share/locale/pt/LC_MESSAGES/bfd.mo 213,241 КиБ
- /usr/share/locale/pt/LC_MESSAGES/binutils.mo 288,055 КиБ
-
-
-
-
- /usr/share/locale/pt_BR/LC_MESSAGES/gprof.mo 10,973 КиБ
- /usr/share/locale/pt_BR/LC_MESSAGES/ld.mo 144,85 КиБ
- /usr/share/locale/pt_BR/LC_MESSAGES/opcodes.mo 55,116 КиБ
-
-
-
-
- /usr/share/locale/ro/LC_MESSAGES/bfd.mo 244,088 КиБ
- /usr/share/locale/ro/LC_MESSAGES/binutils.mo 344,819 КиБ
- /usr/share/locale/ro/LC_MESSAGES/gas.mo 591,549 КиБ
- /usr/share/locale/ro/LC_MESSAGES/gprof.mo 11,214 КиБ
- /usr/share/locale/ro/LC_MESSAGES/ld.mo 184,269 КиБ
- /usr/share/locale/ro/LC_MESSAGES/opcodes.mo 56,448 КиБ
-
-
-
-
- /usr/share/locale/ru/LC_MESSAGES/bfd.mo 291,426 КиБ
- /usr/share/locale/ru/LC_MESSAGES/binutils.mo 333,949 КиБ
- /usr/share/locale/ru/LC_MESSAGES/gas.mo 713,888 КиБ
- /usr/share/locale/ru/LC_MESSAGES/gprof.mo 12,812 КиБ
- /usr/share/locale/ru/LC_MESSAGES/ld.mo 157,21 КиБ
-
-
-
-
- /usr/share/locale/rw/LC_MESSAGES/bfd.mo 429 Б
- /usr/share/locale/rw/LC_MESSAGES/binutils.mo 615 Б
- /usr/share/locale/rw/LC_MESSAGES/gas.mo 396 Б
- /usr/share/locale/rw/LC_MESSAGES/gprof.mo 486 Б
-
-
-
-
- /usr/share/locale/sk/LC_MESSAGES/binutils.mo 146,19 КиБ
-
-
-
-
- /usr/share/locale/sr/LC_MESSAGES/bfd.mo 292,723 КиБ
- /usr/share/locale/sr/LC_MESSAGES/binutils.mo 399,809 КиБ
- /usr/share/locale/sr/LC_MESSAGES/gprof.mo 12,8 КиБ
- /usr/share/locale/sr/LC_MESSAGES/ld.mo 215,922 КиБ
- /usr/share/locale/sr/LC_MESSAGES/opcodes.mo 67,93 КиБ
-
-
-
-
- /usr/share/locale/sv/LC_MESSAGES/bfd.mo 151,621 КиБ
- /usr/share/locale/sv/LC_MESSAGES/binutils.mo 316,367 КиБ
- /usr/share/locale/sv/LC_MESSAGES/gas.mo 512,443 КиБ
- /usr/share/locale/sv/LC_MESSAGES/gprof.mo 10,464 КиБ
- /usr/share/locale/sv/LC_MESSAGES/ld.mo 55,071 КиБ
- /usr/share/locale/sv/LC_MESSAGES/opcodes.mo 52,851 КиБ
-
-
-
-
- /usr/share/locale/tr/LC_MESSAGES/bfd.mo 67,962 КиБ
- /usr/share/locale/tr/LC_MESSAGES/binutils.mo 126,861 КиБ
- /usr/share/locale/tr/LC_MESSAGES/gas.mo 248,881 КиБ
- /usr/share/locale/tr/LC_MESSAGES/gprof.mo 10,746 КиБ
- /usr/share/locale/tr/LC_MESSAGES/ld.mo 52,401 КиБ
- /usr/share/locale/tr/LC_MESSAGES/opcodes.mo 15,779 КиБ
-
-
-
-
- /usr/share/locale/uk/LC_MESSAGES/bfd.mo 306,356 КиБ
- /usr/share/locale/uk/LC_MESSAGES/binutils.mo 406,44 КиБ
- /usr/share/locale/uk/LC_MESSAGES/gas.mo 754,469 КиБ
- /usr/share/locale/uk/LC_MESSAGES/gprof.mo 13,002 КиБ
- /usr/share/locale/uk/LC_MESSAGES/ld.mo 222,812 КиБ
- /usr/share/locale/uk/LC_MESSAGES/opcodes.mo 71,17 КиБ
-
-
-
-
- /usr/share/locale/vi/LC_MESSAGES/bfd.mo 156,623 КиБ
- /usr/share/locale/vi/LC_MESSAGES/binutils.mo 205,308 КиБ
- /usr/share/locale/vi/LC_MESSAGES/gprof.mo 12,254 КиБ
- /usr/share/locale/vi/LC_MESSAGES/ld.mo 60,896 КиБ
- /usr/share/locale/vi/LC_MESSAGES/opcodes.mo 32,885 КиБ
-
-
-
-
- /usr/share/locale/zh_CN/LC_MESSAGES/bfd.mo 17,487 КиБ
- /usr/share/locale/zh_CN/LC_MESSAGES/binutils.mo 90,98 КиБ
- /usr/share/locale/zh_CN/LC_MESSAGES/gas.mo 3,753 КиБ
- /usr/share/locale/zh_CN/LC_MESSAGES/ld.mo 53,092 КиБ
- /usr/share/locale/zh_CN/LC_MESSAGES/opcodes.mo 20,092 КиБ
-
-
-
-
- /usr/share/locale/zh_TW/LC_MESSAGES/binutils.mo 85,807 КиБ
- /usr/share/locale/zh_TW/LC_MESSAGES/ld.mo 53,338 КиБ
-
-
-
-
-
- /usr/share/man/man1/addr2line.1.gz 3,602 КиБ
- /usr/share/man/man1/ar.1.gz 7,052 КиБ
- /usr/share/man/man1/as.1.gz 28,969 КиБ
- /usr/share/man/man1/c++filt.1.gz 3,676 КиБ
- /usr/share/man/man1/dlltool.1.gz 5,584 КиБ
- /usr/share/man/man1/elfedit.1.gz 2,496 КиБ
- /usr/share/man/man1/gprof.1.gz 7,728 КиБ
- /usr/share/man/man1/gprofng-archive.1.gz 3,811 КиБ
- /usr/share/man/man1/gprofng-collect-app.1.gz 3,943 КиБ
- /usr/share/man/man1/gprofng-display-html.1.gz 3,066 КиБ
- /usr/share/man/man1/gprofng-display-src.1.gz 2,293 КиБ
- /usr/share/man/man1/gprofng-display-text.1.gz 4,26 КиБ
- /usr/share/man/man1/gprofng.1.gz 3,121 КиБ
- /usr/share/man/man1/ld.1.gz 46,221 КиБ
- /usr/share/man/man1/nm.1.gz 6,916 КиБ
- /usr/share/man/man1/objcopy.1.gz 13,866 КиБ
- /usr/share/man/man1/objdump.1.gz 14,552 КиБ
- /usr/share/man/man1/ranlib.1.gz 2,093 КиБ
- /usr/share/man/man1/readelf.1.gz 8,307 КиБ
- /usr/share/man/man1/size.1.gz 2,942 КиБ
- /usr/share/man/man1/strings.1.gz 3,717 КиБ
- /usr/share/man/man1/strip.1.gz 4,815 КиБ
- /usr/share/man/man1/windmc.1.gz 2,87 КиБ
- /usr/share/man/man1/windres.1.gz 3,693 КиБ
-
-
-
-
Документация (man-страницы)
OBJDUMP(1) Инструменты разработки GNU OBJDUMP(1)
NAME
objdump - отображение информации из объектных файлов
SYNOPSIS
objdump [-a|--archive-headers]
[-b bfdname|--target=bfdname]
[-C|--demangle[=style] ]
[-d|--disassemble[=symbol]]
[-D|--disassemble-all]
[-z|--disassemble-zeroes]
[-EB|-EL|--endian={big | little }]
[-f|--file-headers]
[-F|--file-offsets]
[--file-start-context]
[-g|--debugging]
[-e|--debugging-tags]
[-h|--section-headers|--headers]
[-i|--info]
[-j section|--section=section]
[-l|--line-numbers]
[-S|--source]
[--source-comment[=text]]
[-m machine|--architecture=machine]
[-M options|--disassembler-options=options]
[-p|--private-headers]
[-P options|--private=options]
[-r|--reloc]
[-R|--dynamic-reloc]
[-s|--full-contents]
[-Z|--decompress]
[-W[lLiaprmfFsoORtUuTgAck]|
--dwarf[=rawline,=decodedline,=info,=abbrev,=pubnames,=aranges,=macro,=frames,=frames-interp,=str,=str-offsets,=loc,=Ranges,=pubtypes,=trace_info,=trace_abbrev,=trace_aranges,=gdb_index,=addr,=cu_index,=links]]
[-WK|--dwarf=follow-links]
[-WN|--dwarf=no-follow-links]
[-wD|--dwarf=use-debuginfod]
[-wE|--dwarf=do-not-use-debuginfod]
[-L|--process-links]
[--ctf=section]
[--sframe=section]
[-G|--stabs]
[-t|--syms]
[-T|--dynamic-syms]
[-x|--all-headers]
[-w|--wide]
[--start-address=address]
[--stop-address=address]
[--no-addresses]
[--prefix-addresses]
[--[no-]show-raw-insn]
[--adjust-vma=offset]
[--show-all-symbols]
[--dwarf-depth=n]
[--dwarf-start=n]
[--ctf-parent=section]
[--no-recurse-limit|--recurse-limit]
[--special-syms]
[--prefix=prefix]
[--prefix-strip=level]
[--insn-width=width]
[--visualize-jumps[=color|=extended-color|=off]
[--disassembler-color=[off|terminal|on|extended]
[-U method] [--unicode=method]
[-V|--version]
[-H|--help]
objfile...
DESCRIPTION
objdump отображает информацию об одном или нескольких объектных файлах. Опции управляют тем, какую именно информацию отображать. Эта информация в основном полезна для программистов, работающих с инструментами компиляции, в отличие от программистов, которые просто хотят скомпилировать и запустить свою программу.
objfile... — это объектные файлы, которые нужно проверить. При указании архивов objdump показывает информацию о каждом объекте внутри архива.
OPTIONS
Длинные и короткие формы опций, показанные здесь как альтернативы, эквивалентны. Должна быть указана хотя бы одна опция из списка -a,-d,-D,-e,-f,-g,-G,-h,-H,-p,-P,-r,-R,-s,-S,-t,-T,-V,-x.
-a
--archive-headers
Если любой из файлов objfile является архивом, отобразить информацию заголовка архива (в формате, похожем на ls -l). Помимо информации, которую можно перечислить с помощью ar tv, objdump -a показывает формат объектного файла для каждого члена архива.
--adjust-vma=offset
При выводе информации сначала добавьте offset ко всем адресам разделов. Это полезно, если адреса разделов не соответствуют таблице символов, что может произойти при размещении разделов по конкретным адресам в формате, который не может представлять адреса разделов, например a.out.
-b bfdname
--target=bfdname
Укажите формат объектного кода для объектных файлов как bfdname. Эта опция может быть не нужна; objdump может автоматически распознавать многие форматы.
Например,
objdump -b oasys -m vax -h fu.o
отображает сводную информацию из заголовков разделов (-h) файла fu.o, который явно идентифицирован (-m) как объектный файл VAX в формате, производимом компиляторами Oasys. Вы можете перечислить доступные форматы с помощью опции -i.
-C
--demangle[=style]
Декодируйте (разъединьте) низкоуровневые имена символов в пользовательские имена. Помимо удаления начального подчеркивания, добавленного системой, это делает читаемыми имена функций C++. Разные компиляторы имеют разные стили пометки. Опциональный аргумент стиля разъединения можно использовать для выбора подходящего стиля пометки для вашего компилятора.
--recurse-limit
--no-recurse-limit
--recursion-limit
--no-recursion-limit
Включает или отключает ограничение на количество рекурсии при разъединении строк. Поскольку форматы пометки имен позволяют бесконечный уровень рекурсии, возможно создать строки, декодирование которых исчерпает объем доступного стека на хост-машине, вызывая ошибку памяти. Ограничение пытается предотвратить это, ограничивая рекурсию до 2048 уровней вложенности.
По умолчанию это ограничение включено, но отключение может быть необходимым для разъединения действительно сложных имен. Обратите внимание, однако, что если ограничение рекурсии отключено, возможен переполнение стека, и любые отчеты об ошибках в таком случае будут отклонены.
-g
--debugging
Отобразить информацию отладки. Это пытается разобрать информацию в формате отладки STABS, хранящуюся в файле, и вывести её в синтаксисе, похожем на C. Если отладочная информация STABS не найдена, эта опция переключается на опцию -W для вывода любой информации DWARF в файле.
-e
--debugging-tags
Как -g, но информация генерируется в формате, совместимом с инструментом ctags.
-d
--disassemble
--disassemble=symbol
Отобразить мнемоники ассемблера для машинных инструкций из входного файла. Эта опция разбирает только те разделы, которые ожидаются содержащими инструкции. Если указан опциональный аргумент symbol, то отобразить мнемоники, начиная с symbol. Если symbol — имя функции, то разбор остановится в конце функции; в противном случае он остановится на следующем символе. Если совпадений для symbol нет, ничего не будет отображено.
Обратите внимание: если опция --dwarf=follow-links включена, то таблицы символов в связанных файлах отладочной информации будут прочитаны и использованы при разборе.
-D
--disassemble-all
Как -d, но разобрать содержимое всех непустых ненулевых разделов, а не только тех, которые ожидаются содержащими инструкции. Опция -j может использоваться для выбора конкретных разделов.
Эта опция также имеет тонкий эффект на разбор инструкций в разделах кода. Когда опция -d активна, objdump предполагает, что любые символы в разделе кода находятся на границе между инструкциями и отказывается разбирать через такую границу. Когда опция -D активна, это предположение подавляется. Это означает, что вывод -d и -D может отличаться, если, например, данные хранятся в разделах кода.
Если цель — архитектура ARM, эта опция также заставляет дизассемблер декодировать фрагменты данных в разделах кода как инструкции.
Обратите внимание: если опция --dwarf=follow-links включена, то таблицы символов в связанных файлах отладочной информации будут прочитаны и использованы при разборе.
--no-addresses
При разборе не выводить адреса на каждой строке или для символов и смещений релокаций. В сочетании с --no-show-raw-insn это может быть полезно для сравнения вывода компилятора.
--prefix-addresses
При разборе выводить полный адрес на каждой строке. Это старый формат разбора.
-EB
-EL
--endian={big|little}
Укажите порядок байт объектных файлов. Это влияет только на разбор. Это может быть полезно при разборе формата файлов, который не описывает информацию о порядке байт, например S-records.
-f
--file-headers
Отобразить сводную информацию из общего заголовка каждого из файлов objfile.
-F
--file-offsets
При разборе разделов, когда отображается символ, также отобразить смещение файла региона данных, который будет выведен. Если пропускаются нули, то при возобновлении разбора сообщите пользователю, сколько нулей было пропущено, и смещение файла места, откуда разбор возобновляется. При выводе разделов отобразить смещение файла места, откуда начинается вывод.
--file-start-context
Укажите, что при отображении чересстрочного исходного кода/разбора (предполагается -S) из файла, который еще не отображался, расширить контекст до начала файла.
-h
--section-headers
--headers
Отобразить сводную информацию из заголовков разделов объектного файла.
Сегменты файлов могут быть перемещены в нестандартные адреса, например, с помощью опций -Ttext, -Tdata или -Tbss для ld. Однако некоторые форматы объектных файлов, такие как a.out, не хранят начальный адрес сегментов файла. В таких ситуациях, хотя ld перемещает разделы правильно, использование objdump -h для перечисления заголовков разделов файла не может показать правильные адреса. Вместо этого оно показывает обычные адреса, которые подразумеваются для цели.
Обратите внимание, в некоторых случаях раздел может иметь как атрибут READONLY, так и NOREAD. В таких случаях атрибут NOREAD имеет приоритет, но objdump сообщит о обоих, поскольку точная установка бит флага может быть важной.
-H
--help
Вывести сводку опций objdump и выйти.
-i
--info
Отобразить список всех доступных архитектур и форматов объектных файлов для указания с -b или -m.
-j name
--section=name
Отобразить информацию для раздела name. Эта опция может быть указана несколько раз.
-L
--process-links
Отобразить содержимое ненулевых разделов, найденных в отдельных файлах отладочной информации, которые связаны с основным файлом. Эта опция автоматически подразумевает опцию -WK, и будут отображаться только разделы, запрошенные другими опциями командной строки.
-l
--line-numbers
Помечать вывод (с помощью информации отладки) именем файла и номерами строк исходного кода, соответствующими объектному коду или релокациям. Полезно только с -d, -D или -r.
-m machine
--architecture=machine
Укажите архитектуру для использования при разборе объектных файлов. Это может быть полезно при разборе объектных файлов, которые не описывают информацию об архитектуре, таких как S-records. Вы можете перечислить доступные архитектуры с помощью опции -i.
Для большинства архитектур можно указать имя архитектуры и имя машины, разделенные двоеточием. Например, foo:bar относится к типу машины bar в архитектуре foo. Это может быть полезно, если objdump настроен на поддержку нескольких архитектур.
Если цель — архитектура ARM, эта опция имеет дополнительный эффект. Она ограничивает разбор только теми инструкциями, которые поддерживаются архитектурой, указанной в machine. Если необходимо использовать эту опцию, потому что входной файл не содержит информации об архитектуре, но также желательно разобрать все инструкции, используйте -marm.
-M options
--disassembler-options=options
Передать целевой информации дизассемблеру. Поддерживается только для некоторых целей. Если необходимо указать несколько опций дизассемблера, можно использовать несколько опций -M или объединить их в список, разделенный запятыми.
Для ARC dsp управляет выводом инструкций DSP, spfp выбирает вывод инструкций FPX одинарной точности, dpfp выбирает вывод инструкций FPX двойной точности, quarkse_em выбирает вывод специальных инструкций QuarkSE-EM, fpuda выбирает вывод инструкций помощи двойной точности, fpus выбирает вывод инструкций FPU одинарной точности, в то время как fpud выбирает вывод инструкций FPU двойной точности. Кроме того, можно выбрать вывод всех непосредственных значений в шестнадцатеричном формате с помощью hex. По умолчанию короткие непосредственные значения выводятся в десятичном представлении, в то время как длинные значения выводятся как шестнадцатеричные.
cpu=... позволяет навязать определенную ISA при разборе инструкций, переопределяя значение -m или то, что указано в ELF-файле. Это может быть полезно для выбора ISA ARC EM или HS, поскольку архитектура одинакова для них, и дизассемблер полагается на частные данные заголовка ELF для решения, является ли код для EM или HS. Эта опция может быть указана несколько раз — будет использоваться только последнее значение. Допустимые значения такие же, как для опции ассемблера -mcpu=... .
Если цель — архитектура ARM, эта опция может использоваться для выбора набора имен регистров, используемого во время дизассемблера. Указание -M reg-names-std (по умолчанию) выберет имена регистров, как в документации по набору инструкций ARM, но с регистром 13, называемым 'sp', регистром 14 — 'lr' и регистром 15 — 'pc'. Указание -M reg-names-apcs выберет набор имен, используемый в стандарте вызова процедур ARM, в то время как указание -M reg-names-raw будет использовать r, за которым следует номер регистра.
Существуют также два варианта набора имен APCS, включенные с -M reg-names-atpcs и -M reg-names-special-atpcs, которые используют соглашения именования стандарта вызова процедур ARM/Thumb. (Либо с обычными именами регистров, либо со специальными именами регистров).
Эта опция также может использоваться для архитектур ARM, чтобы заставить дизассемблер интерпретировать все инструкции как инструкции Thumb с помощью переключателя --disassembler-options=force-thumb. Это может быть полезно при попытке разобрать код Thumb, произведенный другими компиляторами.
Для целей AArch64 этот переключатель может использоваться для установки, отображать ли инструкции как наиболее общие инструкции с опцией -M no-aliases или генерировать ли заметки об инструкциях как комментарии в разборе с -M notes.
Для x86 некоторые опции дублируют функции переключателя -m, но позволяют более точный контроль.
"x86-64"
"i386"
"i8086"
Выбрать разбор для указанной архитектуры.
"intel"
"att"
Выбрать режим синтаксиса intel или режим синтаксиса AT&T.
"amd64"
"intel64"
Выбрать ISA AMD64 или ISA Intel64.
"intel-mnemonic"
"att-mnemonic"
Выбрать режим мнемоники intel или режим мнемоники AT&T. Примечание: "intel-mnemonic" подразумевает "intel", а "att-mnemonic" подразумевает "att".
"addr64"
"addr32"
"addr16"
"data32"
"data16"
Укажите размер адреса и размер операнда по умолчанию. Эти пять опций будут переопределены, если "x86-64", "i386" или "i8086" появятся позже в строке опций.
"suffix"
В режиме AT&T и также для ограниченного набора инструкций в режиме Intel instructs дизассемблер выводить суффикс мнемоники даже когда суффикс может быть выведен из операндов или, для определенных инструкций, из значений по умолчанию режима выполнения.
Для PowerPC аргумент -M raw выбирает разбор аппаратных инструкций, а не псевдонимов. Например, вы увидите "rlwinm" вместо "clrlwi", и "addi" вместо "li". Все аргументы -m для gas, которые выбирают CPU, поддерживаются. Это: 403, 405, 440, 464, 476, 601, 603, 604, 620, 7400, 7410, 7450, 7455, 750cl, 821, 850, 860, a2, booke, booke32, cell, com, e200z2, e200z4, e300, e500, e500mc, e500mc64, e500x2, e5500, e6500, efs, power4, power5, power6, power7, power8, power9, power10, power11, ppc, ppc32, ppc64, ppc64bridge, ppcps, pwr, pwr2, pwr4, pwr5, pwr5x, pwr6, pwr7, pwr8, pwr9, pwr10, pwr11, pwrx, titan, vle, и future. 32 и 64 модифицируют выбор CPU по умолчанию или предыдущий, отключая и включая инструкции 64-бит соответственно. Кроме того, altivec, any, lsp, htm, vsx, spe и spe2 добавляют возможности к предыдущему или последующему выбору CPU. any разберет любую опкоду, известную binutils, но в случаях, когда опкода имеет два разных значения или разные аргументы, вы можете не увидеть ожидаемый разбор. Если вы разберете без выбора CPU, по умолчанию будет выбрано из информации, полученной BFD из заголовков объектных файлов, но результат снова может быть не таким, как ожидалось.
Для MIPS эта опция управляет выводом имен мнемоник инструкций и имен регистров в разобраных инструкциях. Можно указать несколько выборов из следующих как строку, разделенную запятыми, и недопустимые опции игнорируются:
"no-aliases"
Выводить "сырую" мнемонику инструкции вместо некоторой мнемоники псевдоинструкции. Т.е., выводить 'daddu' или 'or' вместо 'move', 'sll' вместо 'nop' и т.д.
"msa"
Разобрать инструкции MSA.
"virt"
Разобрать инструкции виртуализации ASE.
"xpa"
Разобрать инструкции ASE расширенного физического адреса (XPA).
"gpr-names=ABI"
Выводить имена GPR (общие регистры) в соответствии с указанным ABI. По умолчанию имена GPR выбираются в соответствии с ABI двоичного файла, который разбирается.
"fpr-names=ABI"
Выводить имена FPR (регистры с плавающей точкой) в соответствии с указанным ABI. По умолчанию выводятся номера FPR, а не имена.
"cp0-names=ARCH"
Выводить имена регистров CP0 (системный сопроцессор; сопроцессор 0) в соответствии с CPU или архитектурой, указанной в ARCH. По умолчанию имена регистров CP0 выбираются в соответствии с архитектурой и CPU двоичного файла, который разбирается.
"hwr-names=ARCH"
Выводить имена регистров HWR (аппаратный регистр, используемый инструкцией "rdhwr") в соответствии с CPU или архитектурой, указанной в ARCH. По умолчанию имена HWR выбираются в соответствии с архитектурой и CPU двоичного файла, который разбирается.
"reg-names=ABI"
Выводить имена GPR и FPR в соответствии с выбранным ABI.
"reg-names=ARCH"
Выводить имена регистров, специфичные для CPU (имена регистров CP0 и HWR), в соответствии с выбранной CPU или архитектурой.
Для любой из перечисленных выше опций ABI или ARCH можно указать как числовое значение, чтобы выводились числа вместо имен для выбранных типов регистров. Вы можете перечислить доступные значения ABI и ARCH с помощью опции --help.
Для VAX вы можете указывать адреса входа в функцию с -M entry:0xf00ba. Вы можете использовать это несколько раз, чтобы правильно разобрать двоичные файлы VAX, которые не содержат таблиц символов (как дампы ROM). В этих случаях маска входа в функцию в противном случае будет декодирована как инструкции VAX, что, вероятно, приведет к неправильному разбору остальной части функции.
-p
--private-headers
Вывести информацию, специфичную для формата объектного файла. Точная выводимая информация зависит от формата объектного файла. Для некоторых форматов объектных файлов дополнительная информация не выводится.
-P options
--private=options
Вывести информацию, специфичную для формата объектного файла. Аргумент options — список, разделенный запятыми, который зависит от формата (списки опций отображаются с помощью справки).
Для XCOFF доступные опции:
"header"
"aout"
"sections"
"syms"
"relocs"
"lineno,"
"loader"
"except"
"typchk"
"traceback"
"toc"
"ldinfo"
Для PE доступные опции:
"header"
"sections"
Не все форматы объектных файлов поддерживают эту опцию. В частности, формат ELF не использует её.
-r
--reloc
Вывести записи релокаций файла. Если используется с -d или -D, релокации выводятся вперемешку с разбором.
-R
--dynamic-reloc
Вывести динамические записи релокаций файла. Это имеет смысл только для динамических объектов, таких как определенные типы разделяемых библиотек. Как для -r, если используется с -d или -D, релокации выводятся вперемешку с разбором.
-s
--full-contents
Вывести полное содержимое разделов, часто используется в сочетании с -j для запроса конкретных разделов. По умолчанию отображаются все непустые ненулевые разделы. По умолчанию любой сжатый раздел будет отображаться в сжатом виде. Чтобы увидеть содержимое в разжатом виде, добавьте опцию -Z к командной строке.
-S
--source
Отобразить исходный код, перемешанный с разбором, если возможно. Подразумевает -d.
--show-all-symbols
При разборе отображать все символы, которые соответствуют данному адресу, а не только первый.
--source-comment[=txt]
Как опция -S, но все строки исходного кода отображаются с префиксом txt. Обычно txt будет строкой комментария, которая может использоваться для отличия кода ассемблера от кода исходного кода. Если txt не указано, будет использоваться строка по умолчанию "# " (хеш, за которым следует пробел).
--prefix=prefix
Укажите префикс для добавления к абсолютным путям при использовании с -S.
--prefix-strip=level
Укажите, сколько начальных имен каталогов удалить из жестко заданных абсолютных путей. Это не имеет эффекта без --prefix=prefix.
--show-raw-insn
При разборе инструкций выводить инструкцию в шестнадцатеричном формате, а также в символическом виде. Это значение по умолчанию, кроме случаев, когда используется --prefix-addresses.
--no-show-raw-insn
При разборе инструкций не выводить байты инструкции. Это значение по умолчанию, когда используется --prefix-addresses.
--insn-width=width
Выводить width байт в одной строке при разборе инструкций.
--visualize-jumps[=color|=extended-color|=off]
Визуализировать прыжки, которые остаются внутри функции, рисуя ASCII-арт между начальным и целевым адресами. Опциональный аргумент =color добавляет цвет к выводу с помощью простых цветов терминала. В качестве альтернативы аргумент =extended-color добавит цвет с помощью 8-битных цветов, но они могут не работать на всех терминалах.
Если необходимо отключить опцию visualize-jumps после того, как она была ранее включена, используйте visualize-jumps=off.
--disassembler-color=off
--disassembler-color=terminal
--disassembler-color=on|color|colour
--disassembler-color=extened|extended-color|extened-colour
Включает или отключает использование цветного подсветки синтаксиса в выводе разбора. Поведение по умолчанию определяется опцией конфигурации. Обратите внимание, не все архитектуры поддерживают цветную подсветку синтаксиса, и в зависимости от используемого терминала цветной вывод может быть нечитаемым.
Аргумент on добавляет цвета с помощью простых цветов терминала.
Аргумент terminal делает то же самое, но только если устройство вывода — терминал.
Аргумент extended-color похож на аргумент on, но он использует 8-битные цвета. Они могут не работать на всех терминалах.
Аргумент off отключает цветной разбор.
-W[lLiaprmfFsoORtUuTgAckK]
--dwarf[=rawline,=decodedline,=info,=abbrev,=pubnames,=aranges,=macro,=frames,=frames-interp,=str,=str-offsets,=loc,=Ranges,=pubtypes,=trace_info,=trace_abbrev,=trace_aranges,=gdb_index,=addr,=cu_index,=links,=follow-links]
Выводит содержимое разделов отладки DWARF в файле, если они присутствуют. Сжатые разделы отладки автоматически разжимаются (временно) перед отображением. Если за переключателем следует одна или несколько опциональных букв или слов, то будут выведены только эти типы данных. Буквы и слова относятся к следующей информации:
"a"
"=abbrev"
Выводит содержимое раздела .debug_abbrev.
"A"
"=addr"
Выводит содержимое раздела .debug_addr.
"c"
"=cu_index"
Выводит содержимое разделов .debug_cu_index и/или .debug_tu_index.
"f"
"=frames"
Выводит сырое содержимое раздела .debug_frame.
"F"
"=frames-interp"
Выводит интерпретированное содержимое раздела .debug_frame.
"g"
"=gdb_index"
Выводит содержимое разделов .gdb_index и/или .debug_names.
"i"
"=info"
Выводит содержимое раздела .debug_info. Примечание: вывод этой опции также может быть ограничен с помощью опций --dwarf-depth и --dwarf-start.
"k"
"=links"
Выводит содержимое разделов .gnu_debuglink, .gnu_debugaltlink и .debug_sup, если они присутствуют. Также выводит любые ссылки на отдельные объектные файлы dwarf (dwo), если они указаны атрибутами DW_AT_GNU_dwo_name или DW_AT_dwo_name в разделе .debug_info.
"K"
"=follow-links"
Выводит содержимое любых выбранных разделов отладки, найденных в связанных отдельных файлах отладочной информации. Это может привести к нескольким версиям одного и того же раздела отладки, если он существует в нескольких файлах.
Кроме того, при выводе атрибутов DWARF, если найдена форма, которая ссылается на отдельный файл отладочной информации, то ссылочное содержимое также будет отображено.
Примечание — в некоторых дистрибутивах эта опция включена по умолчанию. Её можно отключить через опцию отладки N. Значение по умолчанию можно выбрать при конфигурировании binutils с опциями --enable-follow-debug-links=yes или --enable-follow-debug-links=no. Если они не используются, то по умолчанию включено следование отладочных ссылок.
Примечание — если поддержка протокола debuginfod была включена при сборке binutils, то эта опция также включает попытку связаться с серверами debuginfod, упомянутыми в переменной среды DEBUGINFOD_URLS. Это может занять некоторое время. Это поведение можно отключить через опцию отладки =do-not-use-debuginfod.
"N"
"=no-follow-links"
Отключает следование ссылкам на отдельные файлы отладочной информации.
"D"
"=use-debuginfod"
Включает связь с серверами debuginfod, если нужно следовать отладочным ссылкам. Это поведение по умолчанию.
"E"
"=do-not-use-debuginfod"
Отключает связь с серверами debuginfod, когда нужно следовать отладочным ссылкам.
"l"
"=rawline"
Выводит содержимое раздела .debug_line в сыром формате.
"L"
"=decodedline"
Выводит интерпретированное содержимое раздела .debug_line.
"m"
"=macro"
Выводит содержимое разделов .debug_macro и/или .debug_macinfo.
"o"
"=loc"
Выводит содержимое разделов .debug_loc и/или .debug_loclists.
"O"
"=str-offsets"
Выводит содержимое раздела .debug_str_offsets.
"p"
"=pubnames"
Выводит содержимое разделов .debug_pubnames и/или .debug_gnu_pubnames.
"r"
"=aranges"
Выводит содержимое раздела .debug_aranges.
"R"
"=Ranges"
Выводит содержимое разделов .debug_ranges и/или .debug_rnglists.
"s"
"=str"
Выводит содержимое разделов .debug_str, .debug_line_str и/или .debug_str_offsets.
"t"
"=pubtype"
Выводит содержимое разделов .debug_pubtypes и/или .debug_gnu_pubtypes.
"T"
"=trace_aranges"
Выводит содержимое раздела .trace_aranges.
"u"
"=trace_abbrev"
Выводит содержимое раздела .trace_abbrev.
"U"
"=trace_info"
Выводит содержимое раздела .trace_info.
Примечание: вывод содержимого разделов .debug_static_funcs, .debug_static_vars и debug_weaknames в настоящее время не поддерживается.
--dwarf-depth=n
Ограничить вывод раздела ".debug_info" n детьми. Это полезно только с --debug-dump=info. Значение по умолчанию — выводить все DIE; специальное значение 0 для n также будет иметь этот эффект.
С ненулевым значением n DIE на уровне n или глубже не будут выводиться. Диапазон для n основан на нуле.
--dwarf-start=n
Выводить только DIE, начинающиеся с DIE под номером n. Это полезно только с --debug-dump=info.
Если указано, эта опция подавит вывод любой информации заголовка и всех DIE перед DIE под номером n. Будут выводиться только родственные и дочерние элементы указанного DIE.
Это можно использовать в сочетании с --dwarf-depth.
--dwarf-check
Включить дополнительные проверки на согласованность информации Dwarf.
--ctf[=section]
Вывести содержимое указанного раздела CTF. Разделы CTF сами по себе содержат много подразделов, все из которых выводятся в порядке.
По умолчанию выводить имя раздела .ctf, которое является именем, издаваемым ld.
--ctf-parent=member
Если раздел CTF содержит неоднозначно определенные типы, он будет состоять из архива многих словарей CTF, все из которых наследуют от одного словаря, содержащего неоднозначные типы. Этот член по умолчанию называется .ctf, как и раздел, содержащий его, но возможно изменить это имя с помощью функции "ctf_link_set_memb_name_changer" во время связывания. При просмотре архивов CTF, созданных компоновщиком, который использует переименователь имени для переименования члена родительского архива, --ctf-parent можно использовать для указания имени, используемого для родителя.
--ctf-parent-section=section
Эта опция позволяет выбрать совершенно другой раздел для словаря CTF родителя, содержащего неоднозначные типы, чем для дочерних словарей, которые содержат неоднозначные остатки. Компилятор не генерирует объекты ELF, структурированные таким образом, но некоторые сторонние компоновщики могут. Это также удобно для инспектирования CTF, записанного как несколько необработанных файлов, чтобы составить их с помощью objcopy, который может поместить их в разные разделы ELF, но не в разные члены одного словаря CTF.
--sframe[=section]
Вывести содержимое указанного раздела SFrame.
По умолчанию выводить имя раздела .sframe, которое является именем, издаваемым ld.
-G
--stabs
Вывести полное содержимое любых запрошенных разделов. Вывести содержимое разделов .stab, .stab.index и .stab.excl из ELF-файла. Это полезно только на системах (таких как Solaris 2.0), в которых записи таблицы символов отладки ".stab" хранятся в разделе ELF. В большинстве других форматов файлов записи таблицы символов отладки чередуются с записями таблицы связывания и видны в выводе --syms.
--start-address=address
Начать вывод данных с указанного адреса. Это влияет на вывод опций -d, -r и -s.
--stop-address=address
Остановить вывод данных на указанном адресе. Это влияет на вывод опций -d, -r и -s.
-t
--syms
Вывести записи таблицы символов файла. Это похоже на информацию, предоставляемую программой nm, хотя формат вывода отличается. Формат вывода зависит от формата выводимого файла, но есть два основных типа. Один выглядит так:
[ 4](sec 3)(fl 0x00)(ty 0)(scl 3) (nx 1) 0x00000000 .bss
[ 6](sec 1)(fl 0x00)(ty 0)(scl 2) (nx 0) 0x00000000 fred
где число в квадратных скобках — номер записи в таблице символов, номер sec — номер раздела, значение fl — биты флага символа, номер ty — тип символа, номер scl — класс хранения символа, а значение nx — количество вспомогательных записей, связанных с символом. Последние два поля — значение символа и его имя.
Другой распространенный формат вывода, обычно видимый с файлами на основе ELF, выглядит так:
00000000 l d .bss 00000000 .bss
00000000 g .text 00000000 fred
Здесь первое число — значение символа (иногда называемое его адресом). Следующее поле на самом деле является набором символов и пробелов, указывающих биты флага, установленные для символа. Эти символы описаны ниже. Далее следует раздел, с которым связан символ, или *ABS*, если раздел абсолютный (т.е. не связан ни с каким разделом), или *UND*, если раздел ссылается в выводимом файле, но не определен там.
После имени раздела следует другое поле, число, которое для общих символов является выравниванием, а для других символов — размером. Наконец, выводится имя символа.
Символы флага разделены на 7 групп, как следует:
"l"
"g"
"u"
"!" Символ является локальным (l), глобальным (g), уникально глобальным (u), ни глобальным, ни локальным (пробел) или и глобальным, и локальным (!). Символ может быть ни локальным, ни глобальным по разным причинам, например, потому что он используется для отладки, но это, вероятно, указывает на ошибку, если он когда-либо и глобальный, и локальный. Уникально глобальные символы — это расширение GNU стандартного набора связей символов ELF. Для такого символа динамический компоновщик убедится, что во всем процессе используется только один символ с этим именем и типом.
"w" Символ слабый (w) или сильный (пробел).
"C" Символ обозначает конструктор (C) или обычный символ (пробел).
"W" Символ является предупреждением (W) или обычным символом (пробел). Имя символа предупреждения — сообщение, которое будет отображаться, если символ, следующий за символом предупреждения, когда-либо будет ссылаться.
"I"
"i" Символ является косвенной ссылкой на другой символ (I), функцией, подлежащей оценке во время обработки релокаций (i), или обычным символом (пробел).
"d"
"D" Символ является символом отладки (d) или динамическим символом (D) или обычным символом (пробел).
"F"
"f"
"O" Символ является именем функции (F) или файла (f) или объекта (O) или просто обычным символом (пробел).
-T
--dynamic-syms
Вывести записи динамической таблицы символов файла. Это имеет смысл только для динамических объектов, таких как определенные типы разделяемых библиотек. Это похоже на информацию, предоставляемую программой nm с опцией -D (--dynamic).
Формат вывода похож на тот, который производит опция --syms, за исключением того, что перед именем символа вставляется дополнительное поле, дающее информацию о версии, связанной с символом. Если версия является версией по умолчанию, которая будет использоваться при разрешении неразмеченных ссылок на символ, то она отображается как есть, иначе она помещается в скобки.
--special-syms
При выводе символов включать те, которые цель считает специальными каким-то образом и которые обычно не представляют интереса для пользователя.
-U [d|i|l|e|x|h]
--unicode=[default|invalid|locale|escape|hex|highlight]
Управляет отображением многобайтовых символов, закодированных в UTF-8, в строках. Значение по умолчанию (--unicode=default) — не давать им специального лечения. Опция --unicode=locale отображает последовательность в текущей локали, которая может или не может их поддерживать. Опции --unicode=hex и --unicode=invalid отображаются как последовательности шестнадцатеричных байтов в угловых скобках или фигурных скобках.
Опция --unicode=escape отображает их как последовательности экранирования (\uxxxx), а опция --unicode=highlight отображает их как последовательности экранирования, выделенные красным (если это поддерживается устройством вывода). Цветовое выделение предназначено для привлечения внимания к наличию последовательностей unicode, где они могут не ожидаться.
-V
--version
Вывести номер версии objdump и выйти.
-x
--all-headers
Вывести всю доступную информацию заголовка, включая таблицу символов и записи релокаций. Использование -x эквивалентно указанию всех -a -f -h -p -r -t.
-w
--wide
Форматировать некоторые строки для устройств вывода, имеющих более 80 столбцов. Также не укорачивать имена символов при их отображении.
-z
--disassemble-zeroes
Обычно вывод разбора пропускает блоки нулей. Эта опция направляет дизассемблер разобрать эти блоки, как и любые другие данные.
-Z
--decompress
Опция -Z предназначена для использования в сочетании с опцией -s. Она instructs objdump разжать любые сжатые разделы перед отображением их содержимого.
@file
Читать опции командной строки из файла. Прочитанные опции вставляются на место оригинальной опции @file. Если файл не существует или не может быть прочитан, опция будет рассматриваться буквально и не удаляться.
Опции в файле разделены пробелами. Символ пробела можно включить в опцию, заключая всю опцию в одинарные или двойные кавычки. Любые символы (включая обратную косую черту) можно включить, предваряя символ, который нужно включить, обратной косой чертой. Файл сам может содержать дополнительные опции @file; любые такие опции будут обработаны рекурсивно.
SEE ALSO
nm(1), readelf(1), и записи Info для binutils.
COPYRIGHT
Copyright (c) 1991-2025 Free Software Foundation, Inc.
Разрешается копировать, распространять и/или модифицировать этот документ на условиях Лицензии GNU Free Documentation License, версии 1.3 или любой более поздней версии, опубликованной Free Software Foundation; без Инвариантных Разделов, без Текстов на Обложке и без Текстов на Задней Обложке. Копия лицензии включена в раздел, озаглавленный "GNU Free Documentation License".
binutils-2.44 2025-05-12 OBJDUMP(1)
OBJDUMP(1) GNU Development Tools OBJDUMP(1)
NAME
objdump - display information from object files
SYNOPSIS
objdump [-a|--archive-headers]
[-b bfdname|--target=bfdname]
[-C|--demangle[=style] ]
[-d|--disassemble[=symbol]]
[-D|--disassemble-all]
[-z|--disassemble-zeroes]
[-EB|-EL|--endian={big | little }]
[-f|--file-headers]
[-F|--file-offsets]
[--file-start-context]
[-g|--debugging]
[-e|--debugging-tags]
[-h|--section-headers|--headers]
[-i|--info]
[-j section|--section=section]
[-l|--line-numbers]
[-S|--source]
[--source-comment[=text]]
[-m machine|--architecture=machine]
[-M options|--disassembler-options=options]
[-p|--private-headers]
[-P options|--private=options]
[-r|--reloc]
[-R|--dynamic-reloc]
[-s|--full-contents]
[-Z|--decompress]
[-W[lLiaprmfFsoORtUuTgAck]|
--dwarf[=rawline,=decodedline,=info,=abbrev,=pubnames,=aranges,=macro,=frames,=frames-interp,=str,=str-offsets,=loc,=Ranges,=pubtypes,=trace_info,=trace_abbrev,=trace_aranges,=gdb_index,=addr,=cu_index,=links]]
[-WK|--dwarf=follow-links]
[-WN|--dwarf=no-follow-links]
[-wD|--dwarf=use-debuginfod]
[-wE|--dwarf=do-not-use-debuginfod]
[-L|--process-links]
[--ctf=section]
[--sframe=section]
[-G|--stabs]
[-t|--syms]
[-T|--dynamic-syms]
[-x|--all-headers]
[-w|--wide]
[--start-address=address]
[--stop-address=address]
[--no-addresses]
[--prefix-addresses]
[--[no-]show-raw-insn]
[--adjust-vma=offset]
[--show-all-symbols]
[--dwarf-depth=n]
[--dwarf-start=n]
[--ctf-parent=section]
[--no-recurse-limit|--recurse-limit]
[--special-syms]
[--prefix=prefix]
[--prefix-strip=level]
[--insn-width=width]
[--visualize-jumps[=color|=extended-color|=off]
[--disassembler-color=[off|terminal|on|extended]
[-U method] [--unicode=method]
[-V|--version]
[-H|--help]
objfile...
DESCRIPTION
objdump displays information about one or more object files. The
options control what particular information to display. This
information is mostly useful to programmers who are working on the
compilation tools, as opposed to programmers who just want their
program to compile and work.
objfile... are the object files to be examined. When you specify
archives, objdump shows information on each of the member object files.
OPTIONS
The long and short forms of options, shown here as alternatives, are
equivalent. At least one option from the list
-a,-d,-D,-e,-f,-g,-G,-h,-H,-p,-P,-r,-R,-s,-S,-t,-T,-V,-x must be given.
-a
--archive-header
If any of the objfile files are archives, display the archive
header information (in a format similar to ls -l). Besides the
information you could list with ar tv, objdump -a shows the object
file format of each archive member.
--adjust-vma=offset
When dumping information, first add offset to all the section
addresses. This is useful if the section addresses do not
correspond to the symbol table, which can happen when putting
sections at particular addresses when using a format which can not
represent section addresses, such as a.out.
-b bfdname
--target=bfdname
Specify that the object-code format for the object files is
bfdname. This option may not be necessary; objdump can
automatically recognize many formats.
For example,
objdump -b oasys -m vax -h fu.o
displays summary information from the section headers (-h) of fu.o,
which is explicitly identified (-m) as a VAX object file in the
format produced by Oasys compilers. You can list the formats
available with the -i option.
-C
--demangle[=style]
Decode (demangle) low-level symbol names into user-level names.
Besides removing any initial underscore prepended by the system,
this makes C++ function names readable. Different compilers have
different mangling styles. The optional demangling style argument
can be used to choose an appropriate demangling style for your
compiler.
--recurse-limit
--no-recurse-limit
--recursion-limit
--no-recursion-limit
Enables or disables a limit on the amount of recursion performed
whilst demangling strings. Since the name mangling formats allow
for an infinite level of recursion it is possible to create strings
whose decoding will exhaust the amount of stack space available on
the host machine, triggering a memory fault. The limit tries to
prevent this from happening by restricting recursion to 2048 levels
of nesting.
The default is for this limit to be enabled, but disabling it may
be necessary in order to demangle truly complicated names. Note
however that if the recursion limit is disabled then stack
exhaustion is possible and any bug reports about such an event will
be rejected.
-g
--debugging
Display debugging information. This attempts to parse STABS
debugging format information stored in the file and print it out
using a C like syntax. If no STABS debugging was found this option
falls back on the -W option to print any DWARF information in the
file.
-e
--debugging-tags
Like -g, but the information is generated in a format compatible
with ctags tool.
-d
--disassemble
--disassemble=symbol
Display the assembler mnemonics for the machine instructions from
the input file. This option only disassembles those sections which
are expected to contain instructions. If the optional symbol
argument is given, then display the assembler mnemonics starting at
symbol. If symbol is a function name then disassembly will stop at
the end of the function, otherwise it will stop when the next
symbol is encountered. If there are no matches for symbol then
nothing will be displayed.
Note if the --dwarf=follow-links option is enabled then any symbol
tables in linked debug info files will be read in and used when
disassembling.
-D
--disassemble-all
Like -d, but disassemble the contents of all non-empty non-bss
sections, not just those expected to contain instructions. -j may
be used to select specific sections.
This option also has a subtle effect on the disassembly of
instructions in code sections. When option -d is in effect objdump
will assume that any symbols present in a code section occur on the
boundary between instructions and it will refuse to disassemble
across such a boundary. When option -D is in effect however this
assumption is supressed. This means that it is possible for the
output of -d and -D to differ if, for example, data is stored in
code sections.
If the target is an ARM architecture this switch also has the
effect of forcing the disassembler to decode pieces of data found
in code sections as if they were instructions.
Note if the --dwarf=follow-links option is enabled then any symbol
tables in linked debug info files will be read in and used when
disassembling.
--no-addresses
When disassembling, don't print addresses on each line or for
symbols and relocation offsets. In combination with
--no-show-raw-insn this may be useful for comparing compiler
output.
--prefix-addresses
When disassembling, print the complete address on each line. This
is the older disassembly format.
-EB
-EL
--endian={big|little}
Specify the endianness of the object files. This only affects
disassembly. This can be useful when disassembling a file format
which does not describe endianness information, such as S-records.
-f
--file-headers
Display summary information from the overall header of each of the
objfile files.
-F
--file-offsets
When disassembling sections, whenever a symbol is displayed, also
display the file offset of the region of data that is about to be
dumped. If zeroes are being skipped, then when disassembly
resumes, tell the user how many zeroes were skipped and the file
offset of the location from where the disassembly resumes. When
dumping sections, display the file offset of the location from
where the dump starts.
--file-start-context
Specify that when displaying interlisted source code/disassembly
(assumes -S) from a file that has not yet been displayed, extend
the context to the start of the file.
-h
--section-headers
--headers
Display summary information from the section headers of the object
file.
File segments may be relocated to nonstandard addresses, for
example by using the -Ttext, -Tdata, or -Tbss options to ld.
However, some object file formats, such as a.out, do not store the
starting address of the file segments. In those situations,
although ld relocates the sections correctly, using objdump -h to
list the file section headers cannot show the correct addresses.
Instead, it shows the usual addresses, which are implicit for the
target.
Note, in some cases it is possible for a section to have both the
READONLY and the NOREAD attributes set. In such cases the NOREAD
attribute takes precedence, but objdump will report both since the
exact setting of the flag bits might be important.
-H
--help
Print a summary of the options to objdump and exit.
-i
--info
Display a list showing all architectures and object formats
available for specification with -b or -m.
-j name
--section=name
Display information for section name. This option may be specified
multiple times.
-L
--process-links
Display the contents of non-debug sections found in separate
debuginfo files that are linked to the main file. This option
automatically implies the -WK option, and only sections requested
by other command line options will be displayed.
-l
--line-numbers
Label the display (using debugging information) with the filename
and source line numbers corresponding to the object code or relocs
shown. Only useful with -d, -D, or -r.
-m machine
--architecture=machine
Specify the architecture to use when disassembling object files.
This can be useful when disassembling object files which do not
describe architecture information, such as S-records. You can list
the available architectures with the -i option.
For most architectures it is possible to supply an architecture
name and a machine name, separated by a colon. For example foo:bar
would refer to the bar machine type in the foo architecture. This
can be helpful if objdump has been configured to support multiple
architectures.
If the target is an ARM architecture then this switch has an
additional effect. It restricts the disassembly to only those
instructions supported by the architecture specified by machine.
If it is necessary to use this switch because the input file does
not contain any architecture information, but it is also desired to
disassemble all the instructions use -marm.
-M options
--disassembler-options=options
Pass target specific information to the disassembler. Only
supported on some targets. If it is necessary to specify more than
one disassembler option then multiple -M options can be used or can
be placed together into a comma separated list.
For ARC, dsp controls the printing of DSP instructions, spfp
selects the printing of FPX single precision FP instructions, dpfp
selects the printing of FPX double precision FP instructions,
quarkse_em selects the printing of special QuarkSE-EM instructions,
fpuda selects the printing of double precision assist instructions,
fpus selects the printing of FPU single precision FP instructions,
while fpud selects the printing of FPU double precision FP
instructions. Additionally, one can choose to have all the
immediates printed in hexadecimal using hex. By default, the short
immediates are printed using the decimal representation, while the
long immediate values are printed as hexadecimal.
cpu=... allows one to enforce a particular ISA when disassembling
instructions, overriding the -m value or whatever is in the ELF
file. This might be useful to select ARC EM or HS ISA, because
architecture is same for those and disassembler relies on private
ELF header data to decide if code is for EM or HS. This option
might be specified multiple times - only the latest value will be
used. Valid values are same as for the assembler -mcpu=... option.
If the target is an ARM architecture then this switch can be used
to select which register name set is used during disassembler.
Specifying -M reg-names-std (the default) will select the register
names as used in ARM's instruction set documentation, but with
register 13 called 'sp', register 14 called 'lr' and register 15
called 'pc'. Specifying -M reg-names-apcs will select the name set
used by the ARM Procedure Call Standard, whilst specifying -M reg-
names-raw will just use r followed by the register number.
There are also two variants on the APCS register naming scheme
enabled by -M reg-names-atpcs and -M reg-names-special-atpcs which
use the ARM/Thumb Procedure Call Standard naming conventions.
(Either with the normal register names or the special register
names).
This option can also be used for ARM architectures to force the
disassembler to interpret all instructions as Thumb instructions by
using the switch --disassembler-options=force-thumb. This can be
useful when attempting to disassemble thumb code produced by other
compilers.
For AArch64 targets this switch can be used to set whether
instructions are disassembled as the most general instruction using
the -M no-aliases option or whether instruction notes should be
generated as comments in the disasssembly using -M notes.
For the x86, some of the options duplicate functions of the -m
switch, but allow finer grained control.
"x86-64"
"i386"
"i8086"
Select disassembly for the given architecture.
"intel"
"att"
Select between intel syntax mode and AT&T syntax mode.
"amd64"
"intel64"
Select between AMD64 ISA and Intel64 ISA.
"intel-mnemonic"
"att-mnemonic"
Select between intel mnemonic mode and AT&T mnemonic mode.
Note: "intel-mnemonic" implies "intel" and "att-mnemonic"
implies "att".
"addr64"
"addr32"
"addr16"
"data32"
"data16"
Specify the default address size and operand size. These five
options will be overridden if "x86-64", "i386" or "i8086"
appear later in the option string.
"suffix"
When in AT&T mode and also for a limited set of instructions
when in Intel mode, instructs the disassembler to print a
mnemonic suffix even when the suffix could be inferred by the
operands or, for certain instructions, the execution mode's
defaults.
For PowerPC, the -M argument raw selects disasssembly of hardware
insns rather than aliases. For example, you will see "rlwinm"
rather than "clrlwi", and "addi" rather than "li". All of the -m
arguments for gas that select a CPU are supported. These are: 403,
405, 440, 464, 476, 601, 603, 604, 620, 7400, 7410, 7450, 7455,
750cl, 821, 850, 860, a2, booke, booke32, cell, com, e200z2,
e200z4, e300, e500, e500mc, e500mc64, e500x2, e5500, e6500, efs,
power4, power5, power6, power7, power8, power9, power10, power11,
ppc, ppc32, ppc64, ppc64bridge, ppcps, pwr, pwr2, pwr4, pwr5,
pwr5x, pwr6, pwr7, pwr8, pwr9, pwr10, pwr11, pwrx, titan, vle, and
future. 32 and 64 modify the default or a prior CPU selection,
disabling and enabling 64-bit insns respectively. In addition,
altivec, any, lsp, htm, vsx, spe and spe2 add capabilities to a
previous or later CPU selection. any will disassemble any opcode
known to binutils, but in cases where an opcode has two different
meanings or different arguments, you may not see the disassembly
you expect. If you disassemble without giving a CPU selection, a
default will be chosen from information gleaned by BFD from the
object files headers, but the result again may not be as you
expect.
For MIPS, this option controls the printing of instruction mnemonic
names and register names in disassembled instructions. Multiple
selections from the following may be specified as a comma separated
string, and invalid options are ignored:
"no-aliases"
Print the 'raw' instruction mnemonic instead of some pseudo
instruction mnemonic. I.e., print 'daddu' or 'or' instead of
'move', 'sll' instead of 'nop', etc.
"msa"
Disassemble MSA instructions.
"virt"
Disassemble the virtualization ASE instructions.
"xpa"
Disassemble the eXtended Physical Address (XPA) ASE
instructions.
"gpr-names=ABI"
Print GPR (general-purpose register) names as appropriate for
the specified ABI. By default, GPR names are selected
according to the ABI of the binary being disassembled.
"fpr-names=ABI"
Print FPR (floating-point register) names as appropriate for
the specified ABI. By default, FPR numbers are printed rather
than names.
"cp0-names=ARCH"
Print CP0 (system control coprocessor; coprocessor 0) register
names as appropriate for the CPU or architecture specified by
ARCH. By default, CP0 register names are selected according to
the architecture and CPU of the binary being disassembled.
"hwr-names=ARCH"
Print HWR (hardware register, used by the "rdhwr" instruction)
names as appropriate for the CPU or architecture specified by
ARCH. By default, HWR names are selected according to the
architecture and CPU of the binary being disassembled.
"reg-names=ABI"
Print GPR and FPR names as appropriate for the selected ABI.
"reg-names=ARCH"
Print CPU-specific register names (CP0 register and HWR names)
as appropriate for the selected CPU or architecture.
For any of the options listed above, ABI or ARCH may be specified
as numeric to have numbers printed rather than names, for the
selected types of registers. You can list the available values of
ABI and ARCH using the --help option.
For VAX, you can specify function entry addresses with -M
entry:0xf00ba. You can use this multiple times to properly
disassemble VAX binary files that don't contain symbol tables (like
ROM dumps). In these cases, the function entry mask would
otherwise be decoded as VAX instructions, which would probably lead
the rest of the function being wrongly disassembled.
-p
--private-headers
Print information that is specific to the object file format. The
exact information printed depends upon the object file format. For
some object file formats, no additional information is printed.
-P options
--private=options
Print information that is specific to the object file format. The
argument options is a comma separated list that depends on the
format (the lists of options is displayed with the help).
For XCOFF, the available options are:
"header"
"aout"
"sections"
"syms"
"relocs"
"lineno,"
"loader"
"except"
"typchk"
"traceback"
"toc"
"ldinfo"
For PE, the available options are:
"header"
"sections"
Not all object formats support this option. In particular the ELF
format does not use it.
-r
--reloc
Print the relocation entries of the file. If used with -d or -D,
the relocations are printed interspersed with the disassembly.
-R
--dynamic-reloc
Print the dynamic relocation entries of the file. This is only
meaningful for dynamic objects, such as certain types of shared
libraries. As for -r, if used with -d or -D, the relocations are
printed interspersed with the disassembly.
-s
--full-contents
Display the full contents of sections, often used in combination
with -j to request specific sections. By default all non-empty
non-bss sections are displayed. By default any compressed section
will be displayed in its compressed form. In order to see the
contents in a decompressed form add the -Z option to the command
line.
-S
--source
Display source code intermixed with disassembly, if possible.
Implies -d.
--show-all-symbols
When disassembling, show all the symbols that match a given
address, not just the first one.
--source-comment[=txt]
Like the -S option, but all source code lines are displayed with a
prefix of txt. Typically txt will be a comment string which can be
used to distinguish the assembler code from the source code. If
txt is not provided then a default string of "# " (hash followed by
a space), will be used.
--prefix=prefix
Specify prefix to add to the absolute paths when used with -S.
--prefix-strip=level
Indicate how many initial directory names to strip off the
hardwired absolute paths. It has no effect without --prefix=prefix.
--show-raw-insn
When disassembling instructions, print the instruction in hex as
well as in symbolic form. This is the default except when
--prefix-addresses is used.
--no-show-raw-insn
When disassembling instructions, do not print the instruction
bytes. This is the default when --prefix-addresses is used.
--insn-width=width
Display width bytes on a single line when disassembling
instructions.
--visualize-jumps[=color|=extended-color|=off]
Visualize jumps that stay inside a function by drawing ASCII art
between the start and target addresses. The optional =color
argument adds color to the output using simple terminal colors.
Alternatively the =extended-color argument will add color using
8bit colors, but these might not work on all terminals.
If it is necessary to disable the visualize-jumps option after it
has previously been enabled then use visualize-jumps=off.
--disassembler-color=off
--disassembler-color=terminal
--disassembler-color=on|color|colour
--disassembler-color=extened|extended-color|extened-colour
Enables or disables the use of colored syntax highlighting in
disassembly output. The default behaviour is determined via a
configure time option. Note, not all architectures support colored
syntax highlighting, and depending upon the terminal used, colored
output may not actually be legible.
The on argument adds colors using simple terminal colors.
The terminal argument does the same, but only if the output device
is a terminal.
The extended-color argument is similar to the on argument, but it
uses 8-bit colors. These may not work on all terminals.
The off argument disables colored disassembly.
-W[lLiaprmfFsoORtUuTgAckK]
--dwarf[=rawline,=decodedline,=info,=abbrev,=pubnames,=aranges,=macro,=frames,=frames-interp,=str,=str-offsets,=loc,=Ranges,=pubtypes,=trace_info,=trace_abbrev,=trace_aranges,=gdb_index,=addr,=cu_index,=links,=follow-links]
Displays the contents of the DWARF debug sections in the file, if
any are present. Compressed debug sections are automatically
decompressed (temporarily) before they are displayed. If one or
more of the optional letters or words follows the switch then only
those type(s) of data will be dumped. The letters and words refer
to the following information:
"a"
"=abbrev"
Displays the contents of the .debug_abbrev section.
"A"
"=addr"
Displays the contents of the .debug_addr section.
"c"
"=cu_index"
Displays the contents of the .debug_cu_index and/or
.debug_tu_index sections.
"f"
"=frames"
Display the raw contents of a .debug_frame section.
"F"
"=frames-interp"
Display the interpreted contents of a .debug_frame section.
"g"
"=gdb_index"
Displays the contents of the .gdb_index and/or .debug_names
sections.
"i"
"=info"
Displays the contents of the .debug_info section. Note: the
output from this option can also be restricted by the use of
the --dwarf-depth and --dwarf-start options.
"k"
"=links"
Displays the contents of the .gnu_debuglink, .gnu_debugaltlink
and .debug_sup sections, if any of them are present. Also
displays any links to separate dwarf object files (dwo), if
they are specified by the DW_AT_GNU_dwo_name or DW_AT_dwo_name
attributes in the .debug_info section.
"K"
"=follow-links"
Display the contents of any selected debug sections that are
found in linked, separate debug info file(s). This can result
in multiple versions of the same debug section being displayed
if it exists in more than one file.
In addition, when displaying DWARF attributes, if a form is
found that references the separate debug info file, then the
referenced contents will also be displayed.
Note - in some distributions this option is enabled by default.
It can be disabled via the N debug option. The default can be
chosen when configuring the binutils via the
--enable-follow-debug-links=yes or
--enable-follow-debug-links=no options. If these are not used
then the default is to enable the following of debug links.
Note - if support for the debuginfod protocol was enabled when
the binutils were built then this option will also include an
attempt to contact any debuginfod servers mentioned in the
DEBUGINFOD_URLS environment variable. This could take some
time to resolve. This behaviour can be disabled via the
=do-not-use-debuginfod debug option.
"N"
"=no-follow-links"
Disables the following of links to separate debug info files.
"D"
"=use-debuginfod"
Enables contacting debuginfod servers if there is a need to
follow debug links. This is the default behaviour.
"E"
"=do-not-use-debuginfod"
Disables contacting debuginfod servers when there is a need to
follow debug links.
"l"
"=rawline"
Displays the contents of the .debug_line section in a raw
format.
"L"
"=decodedline"
Displays the interpreted contents of the .debug_line section.
"m"
"=macro"
Displays the contents of the .debug_macro and/or .debug_macinfo
sections.
"o"
"=loc"
Displays the contents of the .debug_loc and/or .debug_loclists
sections.
"O"
"=str-offsets"
Displays the contents of the .debug_str_offsets section.
"p"
"=pubnames"
Displays the contents of the .debug_pubnames and/or
.debug_gnu_pubnames sections.
"r"
"=aranges"
Displays the contents of the .debug_aranges section.
"R"
"=Ranges"
Displays the contents of the .debug_ranges and/or
.debug_rnglists sections.
"s"
"=str"
Displays the contents of the .debug_str, .debug_line_str and/or
.debug_str_offsets sections.
"t"
"=pubtype"
Displays the contents of the .debug_pubtypes and/or
.debug_gnu_pubtypes sections.
"T"
"=trace_aranges"
Displays the contents of the .trace_aranges section.
"u"
"=trace_abbrev"
Displays the contents of the .trace_abbrev section.
"U"
"=trace_info"
Displays the contents of the .trace_info section.
Note: displaying the contents of .debug_static_funcs,
.debug_static_vars and debug_weaknames sections is not currently
supported.
--dwarf-depth=n
Limit the dump of the ".debug_info" section to n children. This is
only useful with --debug-dump=info. The default is to print all
DIEs; the special value 0 for n will also have this effect.
With a non-zero value for n, DIEs at or deeper than n levels will
not be printed. The range for n is zero-based.
--dwarf-start=n
Print only DIEs beginning with the DIE numbered n. This is only
useful with --debug-dump=info.
If specified, this option will suppress printing of any header
information and all DIEs before the DIE numbered n. Only siblings
and children of the specified DIE will be printed.
This can be used in conjunction with --dwarf-depth.
--dwarf-check
Enable additional checks for consistency of Dwarf information.
--ctf[=section]
Display the contents of the specified CTF section. CTF sections
themselves contain many subsections, all of which are displayed in
order.
By default, display the name of the section named .ctf, which is
the name emitted by ld.
--ctf-parent=member
If the CTF section contains ambiguously-defined types, it will
consist of an archive of many CTF dictionaries, all inheriting from
one dictionary containing unambiguous types. This member is by
default named .ctf, like the section containing it, but it is
possible to change this name using the
"ctf_link_set_memb_name_changer" function at link time. When
looking at CTF archives that have been created by a linker that
uses the name changer to rename the parent archive member,
--ctf-parent can be used to specify the name used for the parent.
--ctf-parent-section=section
This option lets you pick a completely different section for the
CTF parent dictionary containing unambiguous types than for the
child dictionaries that contain the ambiguous remainder. The
linker does not emit ELF objects structured like this, but some
third-party linkers may. It's also convenient to inspect CTF
written out as multiple raw files to compose them with objcopy,
which can put them in different ELF sections but not in different
members of a single CTF dict.
--sframe[=section]
Display the contents of the specified SFrame section.
By default, display the name of the section named .sframe, which is
the name emitted by ld.
-G
--stabs
Display the full contents of any sections requested. Display the
contents of the .stab and .stab.index and .stab.excl sections from
an ELF file. This is only useful on systems (such as Solaris 2.0)
in which ".stab" debugging symbol-table entries are carried in an
ELF section. In most other file formats, debugging symbol-table
entries are interleaved with linkage symbols, and are visible in
the --syms output.
--start-address=address
Start displaying data at the specified address. This affects the
output of the -d, -r and -s options.
--stop-address=address
Stop displaying data at the specified address. This affects the
output of the -d, -r and -s options.
-t
--syms
Print the symbol table entries of the file. This is similar to the
information provided by the nm program, although the display format
is different. The format of the output depends upon the format of
the file being dumped, but there are two main types. One looks
like this:
[ 4](sec 3)(fl 0x00)(ty 0)(scl 3) (nx 1) 0x00000000 .bss
[ 6](sec 1)(fl 0x00)(ty 0)(scl 2) (nx 0) 0x00000000 fred
where the number inside the square brackets is the number of the
entry in the symbol table, the sec number is the section number,
the fl value are the symbol's flag bits, the ty number is the
symbol's type, the scl number is the symbol's storage class and the
nx value is the number of auxiliary entries associated with the
symbol. The last two fields are the symbol's value and its name.
The other common output format, usually seen with ELF based files,
looks like this:
00000000 l d .bss 00000000 .bss
00000000 g .text 00000000 fred
Here the first number is the symbol's value (sometimes referred to
as its address). The next field is actually a set of characters
and spaces indicating the flag bits that are set on the symbol.
These characters are described below. Next is the section with
which the symbol is associated or *ABS* if the section is absolute
(ie not connected with any section), or *UND* if the section is
referenced in the file being dumped, but not defined there.
After the section name comes another field, a number, which for
common symbols is the alignment and for other symbol is the size.
Finally the symbol's name is displayed.
The flag characters are divided into 7 groups as follows:
"l"
"g"
"u"
"!" The symbol is a local (l), global (g), unique global (u),
neither global nor local (a space) or both global and local
(!). A symbol can be neither local or global for a variety of
reasons, e.g., because it is used for debugging, but it is
probably an indication of a bug if it is ever both local and
global. Unique global symbols are a GNU extension to the
standard set of ELF symbol bindings. For such a symbol the
dynamic linker will make sure that in the entire process there
is just one symbol with this name and type in use.
"w" The symbol is weak (w) or strong (a space).
"C" The symbol denotes a constructor (C) or an ordinary symbol (a
space).
"W" The symbol is a warning (W) or a normal symbol (a space). A
warning symbol's name is a message to be displayed if the
symbol following the warning symbol is ever referenced.
"I"
"i" The symbol is an indirect reference to another symbol (I), a
function to be evaluated during reloc processing (i) or a
normal symbol (a space).
"d"
"D" The symbol is a debugging symbol (d) or a dynamic symbol (D) or
a normal symbol (a space).
"F"
"f"
"O" The symbol is the name of a function (F) or a file (f) or an
object (O) or just a normal symbol (a space).
-T
--dynamic-syms
Print the dynamic symbol table entries of the file. This is only
meaningful for dynamic objects, such as certain types of shared
libraries. This is similar to the information provided by the nm
program when given the -D (--dynamic) option.
The output format is similar to that produced by the --syms option,
except that an extra field is inserted before the symbol's name,
giving the version information associated with the symbol. If the
version is the default version to be used when resolving
unversioned references to the symbol then it's displayed as is,
otherwise it's put into parentheses.
--special-syms
When displaying symbols include those which the target considers to
be special in some way and which would not normally be of interest
to the user.
-U [d|i|l|e|x|h]
--unicode=[default|invalid|locale|escape|hex|highlight]
Controls the display of UTF-8 encoded multibyte characters in
strings. The default (--unicode=default) is to give them no
special treatment. The --unicode=locale option displays the
sequence in the current locale, which may or may not support them.
The options --unicode=hex and --unicode=invalid display them as hex
byte sequences enclosed by either angle brackets or curly braces.
The --unicode=escape option displays them as escape sequences
(\uxxxx) and the --unicode=highlight option displays them as escape
sequences highlighted in red (if supported by the output device).
The colouring is intended to draw attention to the presence of
unicode sequences where they might not be expected.
-V
--version
Print the version number of objdump and exit.
-x
--all-headers
Display all available header information, including the symbol
table and relocation entries. Using -x is equivalent to specifying
all of -a -f -h -p -r -t.
-w
--wide
Format some lines for output devices that have more than 80
columns. Also do not truncate symbol names when they are
displayed.
-z
--disassemble-zeroes
Normally the disassembly output will skip blocks of zeroes. This
option directs the disassembler to disassemble those blocks, just
like any other data.
-Z
--decompress
The -Z option is meant to be used in conunction with the -s option.
It instructs objdump to decompress any compressed sections before
displaying their contents.
@file
Read command-line options from file. The options read are inserted
in place of the original @file option. If file does not exist, or
cannot be read, then the option will be treated literally, and not
removed.
Options in file are separated by whitespace. A whitespace
character may be included in an option by surrounding the entire
option in either single or double quotes. Any character (including
a backslash) may be included by prefixing the character to be
included with a backslash. The file may itself contain additional
@file options; any such options will be processed recursively.
SEE ALSO
nm(1), readelf(1), and the Info entries for binutils.
COPYRIGHT
Copyright (c) 1991-2025 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3 or
any later version published by the Free Software Foundation; with no
Invariant Sections, with no Front-Cover Texts, and with no Back-Cover
Texts. A copy of the license is included in the section entitled "GNU
Free Documentation License".
binutils-2.44 2025-05-12 OBJDUMP(1)
WINDMC(1) Инструменты разработки GNU WINDMC(1)
NAME
windmc - генерирует ресурсы сообщений Windows
SYNOPSIS
windmc [options] input-file
DESCRIPTION
windmc читает определения сообщений из входного файла (.mc) и переводит
их в набор выходных файлов. Выходные файлы могут быть четырёх видов:
"h" Файл заголовка C, содержащий определения сообщений.
"rc"
Файл ресурсов, компилируемый инструментом windres.
"bin"
Один или несколько бинарных файлов, содержащих данные ресурсов для
конкретного языка сообщений.
"dbg"
Файл включения C, который отображает идентификаторы сообщений в их символическое имя.
Точное описание этих различных форматов доступно в документации от Microsoft.
Когда windmc преобразует из формата "mc" в формат "bin", "rc",
"h" и необязательный "dbg", он действует как Компилятор сообщений Windows.
OPTIONS
-a
--ascii_in
Указывает, что указанный входной файл является ASCII. Это поведение по умолчанию.
-A
--ascii_out
Указывает, что сообщения в выходных файлах "bin" должны быть в формате ASCII.
-b
--binprefix
Указывает, что имена файлов "bin" должны быть с префиксом, равным базовому имени исходного файла.
-c
--customflag
Устанавливает бит клиента во всех идентификаторах сообщений.
-C codepage
--codepage_in codepage
Устанавливает кодовую страницу по умолчанию, которая будет использоваться для преобразования входного файла в UTF16. Значение по умолчанию - кодовая страница 1252.
-d
--decimal_values
Выводит константы в файле заголовка в десятичном формате. Значение по умолчанию - использование шестнадцатеричного вывода.
-e ext
--extension ext
Расширение для файла заголовка. Значение по умолчанию - .h.
-F target
--target target
Указывает формат BFD, который будет использоваться для выходного бинарного файла. Это имя цели BFD; вы можете использовать опцию --help, чтобы увидеть список поддерживаемых целей. Нормально windmc будет использовать формат по умолчанию, который является первым в списке опции --help.
-h path
--headerdir path
Целевая директория для сгенерированного файла заголовка. Значение по умолчанию - текущая директория.
-H
--help
Отображает список опций командной строки и затем выходит.
-m characters
--maxlength characters
Инструктирует windmc генерировать предупреждение, если длина любого сообщения превышает указанное число.
-n
--nullterminate
Завершает текст сообщения в файлах "bin" нулем. По умолчанию они завершаются CR/LF.
-o
--hresult_use
Ещё не реализовано. Инструктирует "windmc" генерировать файл заголовка OLE2, используя определения HRESULT. Статус-коды используются, если флаг не указан.
-O codepage
--codepage_out codepage
Устанавливает кодовую страницу по умолчанию, которая будет использоваться для вывода текстовых файлов. Значение по умолчанию - кодовая страница 1252.
-r path
--rcdir path
Целевая директория для сгенерированного скрипта "rc" и сгенерированных файлов "bin", которые включает скрипт компилятора ресурсов. Значение по умолчанию - текущая директория.
-u
--unicode_in
Указывает, что входной файл является UTF16.
-U
--unicode_out
Указывает, что сообщения в выходном файле "bin" должны быть в формате UTF16. Это поведение по умолчанию.
-v
--verbose
Включает режим подробного вывода.
-V
--version
Печатает номер версии для windmc.
-x path
--xdgb path
Путь к файлу включения C "dbg", который отображает идентификаторы сообщений в символическое имя. Такой файл не генерируется без указания переключателя.
@file
Читает опции командной строки из файла. Прочитанные опции вставляются на место оригинальной опции @file. Если файл не существует или не может быть прочитан, то опция будет обработана буквально и не удалена.
Опции в файле разделены пробелами. Символ пробела может быть включён в опцию путём обрамления всей опции в одинарные или двойные кавычки. Любые символы (включая обратный слэш) могут быть включены путём добавления обратного слэша перед символом, который нужно включить. Файл может сам содержать дополнительные опции @file; такие опции будут обработаны рекурсивно.
SEE ALSO
разделы Info для binutils.
COPYRIGHT
Copyright (c) 1991-2025 Free Software Foundation, Inc.
Разрешается копировать, распространять и/или модифицировать этот документ
в соответствии с условиями Лицензии GNU Free Documentation License, версии 1.3 или любой более поздней версии, опубликованной Free Software Foundation; без Инвариантных Разделов, без Текстов на Обложке и без Текстов на Задней Обложке. Копия лицензии включена в раздел, озаглавленный "GNU Free Documentation License".
binutils-2.44 2025-05-12 WINDMC(1)
WINDMC(1) GNU Development Tools WINDMC(1)
NAME
windmc - generates Windows message resources
SYNOPSIS
windmc [options] input-file
DESCRIPTION
windmc reads message definitions from an input file (.mc) and translate
them into a set of output files. The output files may be of four
kinds:
"h" A C header file containing the message definitions.
"rc"
A resource file compilable by the windres tool.
"bin"
One or more binary files containing the resource data for a
specific message language.
"dbg"
A C include file that maps message id's to their symbolic name.
The exact description of these different formats is available in
documentation from Microsoft.
When windmc converts from the "mc" format to the "bin" format, "rc",
"h", and optional "dbg" it is acting like the Windows Message Compiler.
OPTIONS
-a
--ascii_in
Specifies that the input file specified is ASCII. This is the
default behaviour.
-A
--ascii_out
Specifies that messages in the output "bin" files should be in
ASCII format.
-b
--binprefix
Specifies that "bin" filenames should have to be prefixed by the
basename of the source file.
-c
--customflag
Sets the customer bit in all message id's.
-C codepage
--codepage_in codepage
Sets the default codepage to be used to convert input file to
UTF16. The default is ocdepage 1252.
-d
--decimal_values
Outputs the constants in the header file in decimal. Default is
using hexadecimal output.
-e ext
--extension ext
The extension for the header file. The default is .h extension.
-F target
--target target
Specify the BFD format to use for a bin file as output. This is a
BFD target name; you can use the --help option to see a list of
supported targets. Normally windmc will use the default format,
which is the first one listed by the --help option.
-h path
--headerdir path
The target directory of the generated header file. The default is
the current directory.
-H
--help
Displays a list of command-line options and then exits.
-m characters
--maxlength characters
Instructs windmc to generate a warning if the length of any message
exceeds the number specified.
-n
--nullterminate
Terminate message text in "bin" files by zero. By default they are
terminated by CR/LF.
-o
--hresult_use
Not yet implemented. Instructs "windmc" to generate an OLE2 header
file, using HRESULT definitions. Status codes are used if the flag
is not specified.
-O codepage
--codepage_out codepage
Sets the default codepage to be used to output text files. The
default is ocdepage 1252.
-r path
--rcdir path
The target directory for the generated "rc" script and the
generated "bin" files that the resource compiler script includes.
The default is the current directory.
-u
--unicode_in
Specifies that the input file is UTF16.
-U
--unicode_out
Specifies that messages in the output "bin" file should be in UTF16
format. This is the default behaviour.
-v
--verbose
Enable verbose mode.
-V
--version
Prints the version number for windmc.
-x path
--xdgb path
The path of the "dbg" C include file that maps message id's to the
symbolic name. No such file is generated without specifying the
switch.
@file
Read command-line options from file. The options read are inserted
in place of the original @file option. If file does not exist, or
cannot be read, then the option will be treated literally, and not
removed.
Options in file are separated by whitespace. A whitespace
character may be included in an option by surrounding the entire
option in either single or double quotes. Any character (including
a backslash) may be included by prefixing the character to be
included with a backslash. The file may itself contain additional
@file options; any such options will be processed recursively.
SEE ALSO
the Info entries for binutils.
COPYRIGHT
Copyright (c) 1991-2025 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3 or
any later version published by the Free Software Foundation; with no
Invariant Sections, with no Front-Cover Texts, and with no Back-Cover
Texts. A copy of the license is included in the section entitled "GNU
Free Documentation License".
binutils-2.44 2025-05-12 WINDMC(1)
READELF(1) Инструменты разработки GNU READELF(1)
NAME
readelf - отображение информации об ELF-файлах
SYNOPSIS
readelf [-a|--all]
[-h|--file-header]
[-l|--program-headers|--segments]
[-S|--section-headers|--sections]
[-g|--section-groups]
[-t|--section-details]
[-e|--headers]
[-s|--syms|--symbols]
[--dyn-syms|--lto-syms]
[--sym-base=[0|8|10|16]]
[--demangle=style|--no-demangle]
[--quiet]
[--recurse-limit|--no-recurse-limit]
[-U method|--unicode=method]
[-X|--extra-sym-info|--no-extra-sym-info]
[-n|--notes]
[-r|--relocs]
[-u|--unwind]
[-d|--dynamic]
[-V|--version-info]
[-A|--arch-specific]
[-D|--use-dynamic]
[-L|--lint|--enable-checks]
[-x <number or name>|--hex-dump=<number or name>]
[-p <number or name>|--string-dump=<number or name>]
[-R <number or name>|--relocated-dump=<number or name>]
[-j <number or name>|--display-section=<number or name>]
[-z|--decompress]
[-c|--archive-index]
[-w[lLiaprmfFsoORtUuTgAck]|
--debug-dump[=rawline,=decodedline,=info,=abbrev,=pubnames,=aranges,=macro,=frames,=frames-interp,=str,=str-offsets,=loc,=Ranges,=pubtypes,=trace_info,=trace_abbrev,=trace_aranges,=gdb_index,=addr,=cu_index,=links]]
[-wK|--debug-dump=follow-links]
[-wN|--debug-dump=no-follow-links]
[-wD|--debug-dump=use-debuginfod]
[-wE|--debug-dump=do-not-use-debuginfod]
[-P|--process-links]
[--dwarf-depth=n]
[--dwarf-start=n]
[--ctf=section]
[--ctf-parent=section]
[--ctf-symbols=section]
[--ctf-strings=section]
[--sframe=section]
[-I|--histogram]
[-v|--version]
[-W|--wide]
[-T|--silent-truncation]
[-H|--help]
elffile...
DESCRIPTION
readelf отображает информацию об одном или нескольких объектах в формате ELF.
Опции управляют тем, какую именно информацию отображать.
elffile... являются объектами для анализа. Поддерживаются 32-разрядные и 64-разрядные ELF-файлы,
а также архивы, содержащие ELF-файлы.
Эта программа выполняет функцию, аналогичную objdump, но углубляется в детали и существует независимо от библиотеки BFD,
поэтому, если в BFD есть ошибка, readelf на неё не повлияет.
OPTIONS
Длинные и короткие формы опций, показанные здесь как альтернативы, эквивалентны. Должен быть указан хотя бы один вариант,
кроме -v или -H.
-a
--all
Эквивалентно указанию --file-header, --program-headers,
--sections, --symbols, --relocs, --dynamic, --notes,
--version-info, --arch-specific, --unwind, --section-groups и
--histogram.
Примечание: эта опция сама по себе не включает --use-dynamic, поэтому, если эта опция не указана в командной строке,
динамические символы и динамические релокации не будут отображаться.
-h
--file-header
Отображает информацию, содержащуюся в заголовке ELF в начале файла.
-l
--program-headers
--segments
Отображает информацию, содержащующуюся в заголовках сегментов файла,
если они есть.
--quiet
Подавляет диагностику "no symbols".
-S
--sections
--section-headers
Отображает информацию, содержащующуюся в заголовках разделов файла,
если они есть.
-g
--section-groups
Отображает информацию, содержащующуюся в группах разделов файла, если
они есть.
-t
--section-details
Отображает подробную информацию о разделах. Включает -S.
-s
--symbols
--syms
Отображает записи в разделе таблицы символов файла, если он есть.
Если у символа есть информация о версии, она также отображается.
Строка версии отображается как суффикс к имени символа, предшествуемый символом @.
Например, foo@VER_1. Если версия является версией по умолчанию для разрешения
не versioning ссылок на символ, то она отображается как суффикс, предшествуемый двумя символами @.
Например, foo@@VER_2.
--dyn-syms
Отображает записи в разделе динамической таблицы символов файла,
если он есть. Формат вывода такой же, как у опции --syms.
--lto-syms
Отображает содержимое любых таблиц символов LTO в файле.
--sym-base=[0|8|10|16]
Принудительно использует указанную базу для поля размера в таблице символов.
Любые нераспознанные опции будут рассматриваться как 0. --sym-base=0
представляет значение по умолчанию и прежнее поведение. Это выведет
размеры как десятичные для чисел меньше 100000. Для размеров 100000
и больше будет использоваться шестнадцатеричная нотация с префиксом 0x.
--sym-base=8 выдаст размеры символов в восьмеричной системе. --sym-base=10
всегда выдаст размеры символов в десятичной системе. --sym-base=16
всегда выдаст размеры символов в шестнадцатеричной системе с префиксом 0x.
-C
--demangle[=style]
Декодирует (деменглирует) низкоуровневые имена символов в пользовательские имена.
Это делает имена функций C++ читаемыми. Разные компиляторы имеют разные стили менглинга.
Опциональный аргумент стиля деменглинга может быть использован для выбора подходящего стиля для вашего
компилятора.
--no-demangle
Не деменглировать низкоуровневые имена символов. Это значение по умолчанию.
--recurse-limit
--no-recurse-limit
--recursion-limit
--no-recursion-limit
Включает или отключает ограничение на количество рекурсии при деменглинге строк.
Поскольку форматы именования позволяют бесконечный уровень рекурсии, возможно создать строки,
декодирование которых исчерпает пространство стека на хост-машине, вызвав ошибку памяти.
Ограничение пытается предотвратить это, ограничивая рекурсию до 2048 уровней вложенности.
Значение по умолчанию - включено, но отключение может быть необходимым для деменглинга действительно сложных имён.
Однако, если ограничение рекурсии отключено, возможно исчерпание стека, и любые отчёты об ошибках
такого события будут отклонены.
-U [d|i|l|e|x|h]
--unicode=[default|invalid|locale|escape|hex|highlight]
Управляет отображением не-ASCII символов в именах идентификаторов.
Значение по умолчанию (--unicode=locale или --unicode=default) - treats them as multibyte characters and display them in the current
locale. All other versions of this option treat the bytes as UTF-8
encoded values and attempt to interpret them. If they cannot be
interpreted or if the --unicode=invalid option is used then they
are displayed as a sequence of hex bytes, enclosed in curly
parentheses characters.
Using the --unicode=escape option will display the characters as
unicode escape sequences (\uxxxx). Using the --unicode=hex will
display the characters as hex byte sequences enclosed between angle
brackets.
Using the --unicode=highlight will display the characters as
unicode escape sequences but it will also highlighted them in red,
assuming that colouring is supported by the output device. The
colouring is intended to draw attention to the presence of unicode
sequences when they might not be expected.
-X
--extra-sym-info
When displaying details of symbols, include extra information not
normally presented. Currently this just adds the name of the
section referenced by the symbol's index field, if there is one.
In the future more information may be displayed when this option is
enabled.
Enabling this option effectively enables the --wide option as well,
at least when displaying symbol information.
--no-extra-sym-info
Disables the effect of the --extra-sym-info option. This is the
default.
-e
--headers
Display all the headers in the file. Equivalent to -h -l -S.
-n
--notes
Displays the contents of the NOTE segments and/or sections, if any.
-r
--relocs
Displays the contents of the file's relocation section, if it has
one.
-u
--unwind
Displays the contents of the file's unwind section, if it has one.
Only the unwind sections for IA64 ELF files, as well as ARM unwind
tables (".ARM.exidx" / ".ARM.extab") are currently supported. If
support is not yet implemented for your architecture you could try
dumping the contents of the .eh_frames section using the
--debug-dump=frames or --debug-dump=frames-interp options.
-d
--dynamic
Displays the contents of the file's dynamic section, if it has one.
-V
--version-info
Displays the contents of the version sections in the file, it they
exist.
-A
--arch-specific
Displays architecture-specific information in the file, if there is
any.
-D
--use-dynamic
When displaying symbols, this option makes readelf use the symbol
hash tables in the file's dynamic section, rather than the symbol
table sections.
When displaying relocations, this option makes readelf display the
dynamic relocations rather than the static relocations.
-L
--lint
--enable-checks
Displays warning messages about possible problems with the file(s)
being examined. If used on its own then all of the contents of the
file(s) will be examined. If used with one of the dumping options
then the warning messages will only be produced for the things
being displayed.
-x <number or name>
--hex-dump=<number or name>
Displays the contents of the indicated section as a hexadecimal
bytes. A number identifies a particular section by index in the
section table; any other string identifies all sections with that
name in the object file. This option can be repeated multiple
times on the command line in order to request multiple hex dumps.
-R <number or name>
--relocated-dump=<number or name>
Displays the contents of the indicated section as a hexadecimal
bytes. A number identifies a particular section by index in the
section table; any other string identifies all sections with that
name in the object file. The contents of the section will be
relocated before they are displayed. This option can be repeated
multiple times on the command line in order to request multiple
relocated dumps.
-p <number or name>
--string-dump=<number or name>
Displays the contents of the indicated section as printable
strings. A number identifies a particular section by index in the
section table; any other string identifies all sections with that
name in the object file. This option can be repeated multiple
times on the command line in order to request multiple string
dumps.
-j <number or name>
--display-section
Displays the contents of the indicated section according to its
section header type. Sections containing relocations will be
displayed as if the --relocations option had been used, sections
contains symbols will be displayed as if the --syms option had been
used and so on.
A number identifies a particular section by index in the section
table; any other string identifies all sections with that name in
the input file(s).
This option can be repeated multiple times on the command line in
order to request multiple section dumps.
-z
--decompress
Requests that the section(s) being dumped by x, R or p options are
decompressed before being displayed. If the section(s) are not
compressed then they are displayed as is.
-c
--archive-index
Displays the file symbol index information contained in the header
part of binary archives. Performs the same function as the t
command to ar, but without using the BFD library.
-w[lLiaprmfFsoORtUuTgAckK]
--debug-dump[=rawline,=decodedline,=info,=abbrev,=pubnames,=aranges,=macro,=frames,=frames-interp,=str,=str-offsets,=loc,=Ranges,=pubtypes,=trace_info,=trace_abbrev,=trace_aranges,=gdb_index,=addr,=cu_index,=links,=follow-links]
Displays the contents of the DWARF debug sections in the file, if
any are present. Compressed debug sections are automatically
decompressed (temporarily) before they are displayed. If one or
more of the optional letters or words follows the switch then only
those type(s) of data will be dumped. The letters and words refer
to the following information:
"a"
"=abbrev"
Displays the contents of the .debug_abbrev section.
"A"
"=addr"
Displays the contents of the .debug_addr section.
"c"
"=cu_index"
Displays the contents of the .debug_cu_index and/or
.debug_tu_index sections.
"f"
"=frames"
Display the raw contents of a .debug_frame section.
"F"
"=frames-interp"
Display the interpreted contents of a .debug_frame section.
"g"
"=gdb_index"
Displays the contents of the .gdb_index and/or .debug_names
sections.
"i"
"=info"
Displays the contents of the .debug_info section. Note: the
output from this option can also be restricted by the use of
the --dwarf-depth and --dwarf-start options.
"k"
"=links"
Displays the contents of the .gnu_debuglink, .gnu_debugaltlink
and .debug_sup sections, if any of them are present. Also
displays any links to separate dwarf object files (dwo), if
they are specified by the DW_AT_GNU_dwo_name or DW_AT_dwo_name
attributes in the .debug_info section.
"K"
"=follow-links"
Display the contents of any selected debug sections that are
found in linked, separate debug info file(s). This can result
in multiple versions of the same debug section being displayed
if it exists in more than one file.
In addition, when displaying DWARF attributes, if a form is
found that references the separate debug info file, then the
referenced contents will also be displayed.
Note - in some distributions this option is enabled by default.
It can be disabled via the N debug option. The default can be
chosen when configuring the binutils via the
--enable-follow-debug-links=yes or
--enable-follow-debug-links=no options. If these are not used
then the default is to enable the following of debug links.
Note - if support for the debuginfod protocol was enabled when
the binutils were built then this option will also include an
attempt to contact any debuginfod servers mentioned in the
DEBUGINFOD_URLS environment variable. This could take some
time to resolve. This behaviour can be disabled via the
=do-not-use-debuginfod debug option.
"N"
"=no-follow-links"
Disables the following of links to separate debug info files.
"D"
"=use-debuginfod"
Enables contacting debuginfod servers if there is a need to
follow debug links. This is the default behaviour.
"E"
"=do-not-use-debuginfod"
Disables contacting debuginfod servers when there is a need to
follow debug links.
"l"
"=rawline"
Displays the contents of the .debug_line section in a raw
format.
"L"
"=decodedline"
Displays the interpreted contents of the .debug_line section.
"m"
"=macro"
Displays the contents of the .debug_macro and/or .debug_macinfo
sections.
"o"
"=loc"
Displays the contents of the .debug_loc and/or .debug_loclists
sections.
"O"
"=str-offsets"
Displays the contents of the .debug_str_offsets section.
"p"
"=pubnames"
Displays the contents of the .debug_pubnames and/or
.debug_gnu_pubnames sections.
"r"
"=aranges"
Displays the contents of the .debug_aranges section.
"R"
"=Ranges"
Displays the contents of the .debug_ranges and/or
.debug_rnglists sections.
"s"
"=str"
Displays the contents of the .debug_str, .debug_line_str and/or
.debug_str_offsets sections.
"t"
"=pubtype"
Displays the contents of the .debug_pubtypes and/or
.debug_gnu_pubtypes sections.
"T"
"=trace_aranges"
Displays the contents of the .trace_aranges section.
"u"
"=trace_abbrev"
Displays the contents of the .trace_abbrev section.
"U"
"=trace_info"
Displays the contents of the .trace_info section.
Note: displaying the contents of .debug_static_funcs,
.debug_static_vars and debug_weaknames sections is not currently
supported.
--dwarf-depth=n
Limit the dump of the ".debug_info" section to n children. This is
only useful with --debug-dump=info. The default is to print all
DIEs; the special value 0 for n will also have this effect.
With a non-zero value for n, DIEs at or deeper than n levels will
not be printed. The range for n is zero-based.
--dwarf-start=n
Print only DIEs beginning with the DIE numbered n. This is only
useful with --debug-dump=info.
If specified, this option will suppress printing of any header
information and all DIEs before the DIE numbered n. Only siblings
and children of the specified DIE will be printed.
This can be used in conjunction with --dwarf-depth.
-P
--process-links
Display the contents of non-debug sections found in separate
debuginfo files that are linked to the main file. This option
automatically implies the -wK option, and only sections requested
by other command line options will be displayed.
--ctf[=section]
Display the contents of the specified CTF section. CTF sections
themselves contain many subsections, all of which are displayed in
order.
By default, display the name of the section named .ctf, which is
the name emitted by ld.
--ctf-parent=member
If the CTF section contains ambiguously-defined types, it will
consist of an archive of many CTF dictionaries, all inheriting from
one dictionary containing unambiguous types. This member is by
default named .ctf, like the section containing it, but it is
possible to change this name using the
"ctf_link_set_memb_name_changer" function at link time. When
looking at CTF archives that have been created by a linker that
uses the name changer to rename the parent archive member,
--ctf-parent can be used to specify the name used for the parent.
--ctf-parent-section=section
This option lets you pick a completely different section for the
CTF parent dictionary containing unambiguous types than for the
child dictionaries that contain the ambiguous remainder. The
linker does not emit ELF objects structured like this, but some
third-party linkers may. It's also convenient to inspect CTF
written out as multiple raw files to compose them with objcopy,
which can put them in different ELF sections but not in different
members of a single CTF dict.
--ctf-symbols=section
--ctf-strings=section
Specify the name of another section from which the CTF file can
inherit strings and symbols. By default, the ".symtab" and its
linked string table are used.
If either of --ctf-symbols or --ctf-strings is specified, the other
must be specified as well.
-I
--histogram
Display a histogram of bucket list lengths when displaying the
contents of the symbol tables.
-v
--version
Display the version number of readelf.
-W
--wide
Don't break output lines to fit into 80 columns. By default readelf
breaks section header and segment listing lines for 64-bit ELF
files, so that they fit into 80 columns. This option causes readelf
to print each section header resp. each segment one a single line,
which is far more readable on terminals wider than 80 columns.
-T
--silent-truncation
Normally when readelf is displaying a symbol name, and it has to
truncate the name to fit into an 80 column display, it will add a
suffix of "[...]" to the name. This command line option disables
this behaviour, allowing 5 more characters of the name to be
displayed and restoring the old behaviour of readelf (prior to
release 2.35).
-H
--help
Display the command-line options understood by readelf.
@file
Read command-line options from file. The options read are inserted
in place of the original @file option. If file does not exist, or
cannot be read, then the option will be treated literally, and not
removed.
Options in file are separated by whitespace. A whitespace
character may be included in an option by surrounding the entire
option in either single or double quotes. Any character (including
a backslash) may be included by prefixing the character to be
included with a backslash. The file may itself contain additional
@file options; any such options will be processed recursively.
SEE ALSO
objdump(1), и записи Info для binutils.
COPYRIGHT
Copyright (c) 1991-2025 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3 or
any later version published by the Free Software Foundation; with no
Invariant Sections, with no Front-Cover Texts, and with no Back-Cover
Texts. A copy of the license is included in the section entitled "GNU
Free Documentation License".
binutils-2.44 2025-05-12 READELF(1)
READELF(1) GNU Development Tools READELF(1)
NAME
readelf - display information about ELF files
SYNOPSIS
readelf [-a|--all]
[-h|--file-header]
[-l|--program-headers|--segments]
[-S|--section-headers|--sections]
[-g|--section-groups]
[-t|--section-details]
[-e|--headers]
[-s|--syms|--symbols]
[--dyn-syms|--lto-syms]
[--sym-base=[0|8|10|16]]
[--demangle=style|--no-demangle]
[--quiet]
[--recurse-limit|--no-recurse-limit]
[-U method|--unicode=method]
[-X|--extra-sym-info|--no-extra-sym-info]
[-n|--notes]
[-r|--relocs]
[-u|--unwind]
[-d|--dynamic]
[-V|--version-info]
[-A|--arch-specific]
[-D|--use-dynamic]
[-L|--lint|--enable-checks]
[-x <number or name>|--hex-dump=<number or name>]
[-p <number or name>|--string-dump=<number or name>]
[-R <number or name>|--relocated-dump=<number or name>]
[-j <number or name>|--display-section=<number or name>]
[-z|--decompress]
[-c|--archive-index]
[-w[lLiaprmfFsoORtUuTgAck]|
--debug-dump[=rawline,=decodedline,=info,=abbrev,=pubnames,=aranges,=macro,=frames,=frames-interp,=str,=str-offsets,=loc,=Ranges,=pubtypes,=trace_info,=trace_abbrev,=trace_aranges,=gdb_index,=addr,=cu_index,=links]]
[-wK|--debug-dump=follow-links]
[-wN|--debug-dump=no-follow-links]
[-wD|--debug-dump=use-debuginfod]
[-wE|--debug-dump=do-not-use-debuginfod]
[-P|--process-links]
[--dwarf-depth=n]
[--dwarf-start=n]
[--ctf=section]
[--ctf-parent=section]
[--ctf-symbols=section]
[--ctf-strings=section]
[--sframe=section]
[-I|--histogram]
[-v|--version]
[-W|--wide]
[-T|--silent-truncation]
[-H|--help]
elffile...
DESCRIPTION
readelf displays information about one or more ELF format object files.
The options control what particular information to display.
elffile... are the object files to be examined. 32-bit and 64-bit ELF
files are supported, as are archives containing ELF files.
This program performs a similar function to objdump but it goes into
more detail and it exists independently of the BFD library, so if there
is a bug in BFD then readelf will not be affected.
OPTIONS
The long and short forms of options, shown here as alternatives, are
equivalent. At least one option besides -v or -H must be given.
-a
--all
Equivalent to specifying --file-header, --program-headers,
--sections, --symbols, --relocs, --dynamic, --notes,
--version-info, --arch-specific, --unwind, --section-groups and
--histogram.
Note - this option does not enable --use-dynamic itself, so if that
option is not present on the command line then dynamic symbols and
dynamic relocs will not be displayed.
-h
--file-header
Displays the information contained in the ELF header at the start
of the file.
-l
--program-headers
--segments
Displays the information contained in the file's segment headers,
if it has any.
--quiet
Suppress "no symbols" diagnostic.
-S
--sections
--section-headers
Displays the information contained in the file's section headers,
if it has any.
-g
--section-groups
Displays the information contained in the file's section groups, if
it has any.
-t
--section-details
Displays the detailed section information. Implies -S.
-s
--symbols
--syms
Displays the entries in symbol table section of the file, if it has
one. If a symbol has version information associated with it then
this is displayed as well. The version string is displayed as a
suffix to the symbol name, preceded by an @ character. For example
foo@VER_1. If the version is the default version to be used when
resolving unversioned references to the symbol then it is displayed
as a suffix preceded by two @ characters. For example foo@@VER_2.
--dyn-syms
Displays the entries in dynamic symbol table section of the file,
if it has one. The output format is the same as the format used by
the --syms option.
--lto-syms
Displays the contents of any LTO symbol tables in the file.
--sym-base=[0|8|10|16]
Forces the size field of the symbol table to use the given base.
Any unrecognized options will be treated as 0. --sym-base=0
represents the default and legacy behaviour. This will output
sizes as decimal for numbers less than 100000. For sizes 100000
and greater hexadecimal notation will be used with a 0x prefix.
--sym-base=8 will give the symbol sizes in octal. --sym-base=10
will always give the symbol sizes in decimal. --sym-base=16 will
always give the symbol sizes in hexadecimal with a 0x prefix.
-C
--demangle[=style]
Decode (demangle) low-level symbol names into user-level names.
This makes C++ function names readable. Different compilers have
different mangling styles. The optional demangling style argument
can be used to choose an appropriate demangling style for your
compiler.
--no-demangle
Do not demangle low-level symbol names. This is the default.
--recurse-limit
--no-recurse-limit
--recursion-limit
--no-recursion-limit
Enables or disables a limit on the amount of recursion performed
whilst demangling strings. Since the name mangling formats allow
for an infinite level of recursion it is possible to create strings
whose decoding will exhaust the amount of stack space available on
the host machine, triggering a memory fault. The limit tries to
prevent this from happening by restricting recursion to 2048 levels
of nesting.
The default is for this limit to be enabled, but disabling it may
be necessary in order to demangle truly complicated names. Note
however that if the recursion limit is disabled then stack
exhaustion is possible and any bug reports about such an event will
be rejected.
-U [d|i|l|e|x|h]
--unicode=[default|invalid|locale|escape|hex|highlight]
Controls the display of non-ASCII characters in identifier names.
The default (--unicode=locale or --unicode=default) is to treat
them as multibyte characters and display them in the current
locale. All other versions of this option treat the bytes as UTF-8
encoded values and attempt to interpret them. If they cannot be
interpreted or if the --unicode=invalid option is used then they
are displayed as a sequence of hex bytes, encloses in curly
parethesis characters.
Using the --unicode=escape option will display the characters as as
unicode escape sequences (\uxxxx). Using the --unicode=hex will
display the characters as hex byte sequences enclosed between angle
brackets.
Using the --unicode=highlight will display the characters as
unicode escape sequences but it will also highlighted them in red,
assuming that colouring is supported by the output device. The
colouring is intended to draw attention to the presence of unicode
sequences when they might not be expected.
-X
--extra-sym-info
When displaying details of symbols, include extra information not
normally presented. Currently this just adds the name of the
section referenced by the symbol's index field, if there is one.
In the future more information may be displayed when this option is
enabled.
Enabling this option effectively enables the --wide option as well,
at least when displaying symbol information.
--no-extra-sym-info
Disables the effect of the --extra-sym-info option. This is the
default.
-e
--headers
Display all the headers in the file. Equivalent to -h -l -S.
-n
--notes
Displays the contents of the NOTE segments and/or sections, if any.
-r
--relocs
Displays the contents of the file's relocation section, if it has
one.
-u
--unwind
Displays the contents of the file's unwind section, if it has one.
Only the unwind sections for IA64 ELF files, as well as ARM unwind
tables (".ARM.exidx" / ".ARM.extab") are currently supported. If
support is not yet implemented for your architecture you could try
dumping the contents of the .eh_frames section using the
--debug-dump=frames or --debug-dump=frames-interp options.
-d
--dynamic
Displays the contents of the file's dynamic section, if it has one.
-V
--version-info
Displays the contents of the version sections in the file, it they
exist.
-A
--arch-specific
Displays architecture-specific information in the file, if there is
any.
-D
--use-dynamic
When displaying symbols, this option makes readelf use the symbol
hash tables in the file's dynamic section, rather than the symbol
table sections.
When displaying relocations, this option makes readelf display the
dynamic relocations rather than the static relocations.
-L
--lint
--enable-checks
Displays warning messages about possible problems with the file(s)
being examined. If used on its own then all of the contents of the
file(s) will be examined. If used with one of the dumping options
then the warning messages will only be produced for the things
being displayed.
-x <number or name>
--hex-dump=<number or name>
Displays the contents of the indicated section as a hexadecimal
bytes. A number identifies a particular section by index in the
section table; any other string identifies all sections with that
name in the object file. This option can be repeated multiple
times on the command line in order to request multiple hex dumps.
-R <number or name>
--relocated-dump=<number or name>
Displays the contents of the indicated section as a hexadecimal
bytes. A number identifies a particular section by index in the
section table; any other string identifies all sections with that
name in the object file. The contents of the section will be
relocated before they are displayed. This option can be repeated
multiple times on the command line in order to request multiple
relocated dumps.
-p <number or name>
--string-dump=<number or name>
Displays the contents of the indicated section as printable
strings. A number identifies a particular section by index in the
section table; any other string identifies all sections with that
name in the object file. This option can be repeated multiple
times on the command line in order to request multiple string
dumps.
-j <number or name>
--display-section
Displays the contents of the indicated section according to its
section header type. Sections containing relocations will be
displayed as if the --relocations option had been used, sections
contains symbols will be displayed as if the --syms option had been
used and so on.
A number identifies a particular section by index in the section
table; any other string identifies all sections with that name in
the input file(s).
This option can be repeated multiple times on the command line in
order to request multiple section dumps.
-z
--decompress
Requests that the section(s) being dumped by x, R or p options are
decompressed before being displayed. If the section(s) are not
compressed then they are displayed as is.
-c
--archive-index
Displays the file symbol index information contained in the header
part of binary archives. Performs the same function as the t
command to ar, but without using the BFD library.
-w[lLiaprmfFsOoRtUuTgAckK]
--debug-dump[=rawline,=decodedline,=info,=abbrev,=pubnames,=aranges,=macro,=frames,=frames-interp,=str,=str-offsets,=loc,=Ranges,=pubtypes,=trace_info,=trace_abbrev,=trace_aranges,=gdb_index,=addr,=cu_index,=links,=follow-links]
Displays the contents of the DWARF debug sections in the file, if
any are present. Compressed debug sections are automatically
decompressed (temporarily) before they are displayed. If one or
more of the optional letters or words follows the switch then only
those type(s) of data will be dumped. The letters and words refer
to the following information:
"a"
"=abbrev"
Displays the contents of the .debug_abbrev section.
"A"
"=addr"
Displays the contents of the .debug_addr section.
"c"
"=cu_index"
Displays the contents of the .debug_cu_index and/or
.debug_tu_index sections.
"f"
"=frames"
Display the raw contents of a .debug_frame section.
"F"
"=frames-interp"
Display the interpreted contents of a .debug_frame section.
"g"
"=gdb_index"
Displays the contents of the .gdb_index and/or .debug_names
sections.
"i"
"=info"
Displays the contents of the .debug_info section. Note: the
output from this option can also be restricted by the use of
the --dwarf-depth and --dwarf-start options.
"k"
"=links"
Displays the contents of the .gnu_debuglink, .gnu_debugaltlink
and .debug_sup sections, if any of them are present. Also
displays any links to separate dwarf object files (dwo), if
they are specified by the DW_AT_GNU_dwo_name or DW_AT_dwo_name
attributes in the .debug_info section.
"K"
"=follow-links"
Display the contents of any selected debug sections that are
found in linked, separate debug info file(s). This can result
in multiple versions of the same debug section being displayed
if it exists in more than one file.
In addition, when displaying DWARF attributes, if a form is
found that references the separate debug info file, then the
referenced contents will also be displayed.
Note - in some distributions this option is enabled by default.
It can be disabled via the N debug option. The default can be
chosen when configuring the binutils via the
--enable-follow-debug-links=yes or
--enable-follow-debug-links=no options. If these are not used
then the default is to enable the following of debug links.
Note - if support for the debuginfod protocol was enabled when
the binutils were built then this option will also include an
attempt to contact any debuginfod servers mentioned in the
DEBUGINFOD_URLS environment variable. This could take some
time to resolve. This behaviour can be disabled via the
=do-not-use-debuginfod debug option.
"N"
"=no-follow-links"
Disables the following of links to separate debug info files.
"D"
"=use-debuginfod"
Enables contacting debuginfod servers if there is a need to
follow debug links. This is the default behaviour.
"E"
"=do-not-use-debuginfod"
Disables contacting debuginfod servers when there is a need to
follow debug links.
"l"
"=rawline"
Displays the contents of the .debug_line section in a raw
format.
"L"
"=decodedline"
Displays the interpreted contents of the .debug_line section.
"m"
"=macro"
Displays the contents of the .debug_macro and/or .debug_macinfo
sections.
"o"
"=loc"
Displays the contents of the .debug_loc and/or .debug_loclists
sections.
"O"
"=str-offsets"
Displays the contents of the .debug_str_offsets section.
"p"
"=pubnames"
Displays the contents of the .debug_pubnames and/or
.debug_gnu_pubnames sections.
"r"
"=aranges"
Displays the contents of the .debug_aranges section.
"R"
"=Ranges"
Displays the contents of the .debug_ranges and/or
.debug_rnglists sections.
"s"
"=str"
Displays the contents of the .debug_str, .debug_line_str and/or
.debug_str_offsets sections.
"t"
"=pubtype"
Displays the contents of the .debug_pubtypes and/or
.debug_gnu_pubtypes sections.
"T"
"=trace_aranges"
Displays the contents of the .trace_aranges section.
"u"
"=trace_abbrev"
Displays the contents of the .trace_abbrev section.
"U"
"=trace_info"
Displays the contents of the .trace_info section.
Note: displaying the contents of .debug_static_funcs,
.debug_static_vars and debug_weaknames sections is not currently
supported.
--dwarf-depth=n
Limit the dump of the ".debug_info" section to n children. This is
only useful with --debug-dump=info. The default is to print all
DIEs; the special value 0 for n will also have this effect.
With a non-zero value for n, DIEs at or deeper than n levels will
not be printed. The range for n is zero-based.
--dwarf-start=n
Print only DIEs beginning with the DIE numbered n. This is only
useful with --debug-dump=info.
If specified, this option will suppress printing of any header
information and all DIEs before the DIE numbered n. Only siblings
and children of the specified DIE will be printed.
This can be used in conjunction with --dwarf-depth.
-P
--process-links
Display the contents of non-debug sections found in separate
debuginfo files that are linked to the main file. This option
automatically implies the -wK option, and only sections requested
by other command line options will be displayed.
--ctf[=section]
Display the contents of the specified CTF section. CTF sections
themselves contain many subsections, all of which are displayed in
order.
By default, display the name of the section named .ctf, which is
the name emitted by ld.
--ctf-parent=member
If the CTF section contains ambiguously-defined types, it will
consist of an archive of many CTF dictionaries, all inheriting from
one dictionary containing unambiguous types. This member is by
default named .ctf, like the section containing it, but it is
possible to change this name using the
"ctf_link_set_memb_name_changer" function at link time. When
looking at CTF archives that have been created by a linker that
uses the name changer to rename the parent archive member,
--ctf-parent can be used to specify the name used for the parent.
--ctf-parent-section=section
This option lets you pick a completely different section for the
CTF parent dictionary containing unambiguous types than for the
child dictionaries that contain the ambiguous remainder. The
linker does not emit ELF objects structured like this, but some
third-party linkers may. It's also convenient to inspect CTF
written out as multiple raw files to compose them with objcopy,
which can put them in different ELF sections but not in different
members of a single CTF dict.
--ctf-symbols=section
--ctf-strings=section
Specify the name of another section from which the CTF file can
inherit strings and symbols. By default, the ".symtab" and its
linked string table are used.
If either of --ctf-symbols or --ctf-strings is specified, the other
must be specified as well.
-I
--histogram
Display a histogram of bucket list lengths when displaying the
contents of the symbol tables.
-v
--version
Display the version number of readelf.
-W
--wide
Don't break output lines to fit into 80 columns. By default readelf
breaks section header and segment listing lines for 64-bit ELF
files, so that they fit into 80 columns. This option causes readelf
to print each section header resp. each segment one a single line,
which is far more readable on terminals wider than 80 columns.
-T
--silent-truncation
Normally when readelf is displaying a symbol name, and it has to
truncate the name to fit into an 80 column display, it will add a
suffix of "[...]" to the name. This command line option disables
this behaviour, allowing 5 more characters of the name to be
displayed and restoring the old behaviour of readelf (prior to
release 2.35).
-H
--help
Display the command-line options understood by readelf.
@file
Read command-line options from file. The options read are inserted
in place of the original @file option. If file does not exist, or
cannot be read, then the option will be treated literally, and not
removed.
Options in file are separated by whitespace. A whitespace
character may be included in an option by surrounding the entire
option in either single or double quotes. Any character (including
a backslash) may be included by prefixing the character to be
included with a backslash. The file may itself contain additional
@file options; any such options will be processed recursively.
SEE ALSO
objdump(1), and the Info entries for binutils.
COPYRIGHT
Copyright (c) 1991-2025 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3 or
any later version published by the Free Software Foundation; with no
Invariant Sections, with no Front-Cover Texts, and with no Back-Cover
Texts. A copy of the license is included in the section entitled "GNU
Free Documentation License".
binutils-2.44 2025-05-12 READELF(1)
LD(1) Инструменты разработки GNU LD(1)
NAME
ld - Связыватель GNU
SYNOPSIS
ld [options] objfile ...
DESCRIPTION
ld объединяет несколько объектных и архивных файлов, перераспределяет их данные
и связывает ссылки на символы. Обычно это последний шаг при компиляции программы —
запуск ld.
ld принимает файлы языка команд связывателя, написанные в надмножестве синтаксиса
Link Editor Command Language от AT&T, для обеспечения явного и полного контроля
над процессом связывания.
Эта страница man не описывает язык команд; см. раздел ld в "info" для полной информации
о языке команд и других аспектах связывателя GNU.
Эта версия ld использует библиотеки общего назначения BFD для работы с
объектными файлами. Это позволяет ld читать, объединять и записывать объектные файлы
в различных форматах — например, COFF или "a.out". Разные форматы могут быть связаны
вместе для получения любого доступного вида объектного файла.
Помимо своей гибкости, связыватель GNU более полезен, чем другие связыватели, в предоставлении
диагностической информации. Многие связыватели прекращают выполнение сразу же при возникновении
ошибки; по возможности ld продолжает выполнение, позволяя выявить другие ошибки (или, в некоторых
случаях, получить выходной файл несмотря на ошибку).
Связыватель GNU ld предназначен для охвата широкого спектра ситуаций и обеспечения максимальной
совместимости с другими связывателями. В результате у вас есть множество выборов для контроля
его поведения.
OPTIONS
Связыватель поддерживает множество командных опций командной строки, но на практике
немногие из них используются в определённом контексте. Например, частое использование ld
— связывание стандартных объектных файлов Unix на стандартной, поддерживаемой системе Unix.
На такой системе, чтобы связать файл "hello.o":
ld -o <output> /lib/crt0.o hello.o -lc
Это указывает ld создать файл под названием output как результат связывания файла "/lib/crt0.o"
с "hello.o" и библиотекой "libc.a", которая будет взята из стандартных каталогов поиска.
(См. обсуждение опции -l ниже.)
Некоторые опции командной строки ld могут быть указаны в любой точке командной строки.
Однако опции, которые относятся к файлам, такие как -l или -T, заставляют файл быть прочитанным
в точке, где опция появляется в командной строке, относительно объектных файлов и других
опций файлов. Повторение нефайловых опций с другим аргументом либо не окажет дальнейшего эффекта,
либо переопределит предыдущие появления (те, что дальше влево в командной строке) этой опции.
Опции, которые могут быть осмысленно указаны более одного раза, отмечены в описаниях ниже.
Аргументы, не являющиеся опциями, — это объектные файлы или архивы, которые должны быть
связаны вместе. Они могут следовать, предшествовать или перемешиваться с опциями командной строки,
за исключением того, что аргумент объектного файла не может быть размещён между опцией и её
аргументом.
Обычно связыватель вызывается как минимум с одним объектным файлом, но вы можете указать
другие формы бинарных входных файлов с помощью -l, -R и языка команд скрипта. Если вообще
не указаны бинарные входные файлы, связыватель не производит никакого вывода и выдаёт
сообщение No input files.
Если связыватель не может распознать формат объектного файла, он предположит, что это
скрипт связывателя. Скрипт, указанный таким образом, дополняет основной скрипт связывателя,
используемый для связывания (либо скрипт связывателя по умолчанию, либо тот, который указан
с помощью -T). Эта функция позволяет связывателю связывать файл, который выглядит как объект
или архив, но на самом деле лишь определяет некоторые значения символов или использует
"INPUT" или "GROUP" для загрузки других объектов. Указание скрипта таким образом дополняет
основной скрипт связывателя, с дополнительными командами, размещёнными после основного
скрипта; используйте опцию -T для полной замены скрипта связывателя по умолчанию, но учтите
эффект команды "INSERT".
Для опций, имена которых состоят из одной буквы, аргументы опций должны либо следовать
за буквой опции без промежуточных пробелов, либо указываться как отдельные аргументы
непосредственно после опции, которая их требует.
Для опций, имена которых состоят из нескольких букв, перед именем опции может стоять
либо один дефис, либо два; например, -trace-symbol и --trace-symbol эквивалентны.
Замечание — есть одно исключение из этого правила. Опции с несколькими буквами, начинающиеся
с маленькой буквы 'o', могут предшествовать только двум дефисам. Это для снижения путаницы
с опцией -o. Таким образом, например, -omagic устанавливает имя выходного файла в magic,
в то время как --omagic устанавливает флаг NMAGIC на выходе.
Аргументы для опций с несколькими буквами должны либо отделяться от имени опции знаком
равенства, либо указываться как отдельные аргументы непосредственно после опции, которая
их требует. Например, --trace-symbol foo и --trace-symbol=foo эквивалентны. Уникальные
сокращения имён опций с несколькими буквами принимаются.
Замечание — если связыватель вызывается косвенно, через драйвер компилятора (например, gcc),
то все опции командной строки связывателя должны предшествовать -Wl, (или чему-то подходящему
для конкретного драйвера компилятора), например так:
gcc -Wl,--start-group foo.o bar.o -Wl,--end-group
Это важно, потому что программа-драйвер компилятора может тихо отбросить опции связывателя,
что приведёт к неудачному связыванию. Возникает путаница также при передаче опций, требующих
значений, через драйвер, поскольку использование пробела между опцией и аргументом действует
как разделитель и заставляет драйвер передавать только опцию связывателю, а аргумент —
компилятору. В этом случае проще использовать объединённые формы как одиночных, так и
множественных опций, например:
gcc foo.o bar.o -Wl,-eENTRY -Wl,-Map=a.map
Вот таблица общих опций командной строки, принимаемых связывателем GNU:
@file
Читать опции командной строки из file. Опции, прочитанные из файла, вставляются
на место оригинальной опции @file. Если file не существует или не может быть прочитан,
опция будет обработана буквально, без удаления.
Опции в file разделены пробелами. Пробельный символ может быть включён в опцию,
если вся опция окружена одиночными или двойными кавычками. Любые символы (включая
обратную косую черту) могут быть включены путём добавления перед ними обратной косой
черты. Файл может сам содержать дополнительные опции @file; такие опции будут
обработаны рекурсивно.
-a keyword
Эта опция поддерживается для совместимости с HP/UX. Аргумент keyword должен быть
одной из строк: archive, shared или default. -aarchive эквивалентна -Bstatic,
а другие две строки эквивалентны -Bdynamic. Эта опция может использоваться
любое количество раз.
--audit AUDITLIB
Добавляет AUDITLIB в запись "DT_AUDIT" раздела динамических ссылок. AUDITLIB
не проверяется на существование, и она не будет использовать DT_SONAME, указанное
в библиотеке. Если указано несколько раз, "DT_AUDIT" будет содержать список
интерфейсов аудита, разделённый двоеточиями. Если связыватель находит объект
с записью аудита при поиске разделяемых библиотек, он добавит соответствующую
запись "DT_DEPAUDIT" в выходной файл. Эта опция осмысленна только на платформах
ELF, поддерживающих интерфейс rtld-audit.
-b input-format
--format=input-format
ld может быть настроен для поддержки нескольких видов объектных файлов. Если
ваш ld настроен таким образом, вы можете использовать опцию -b для указания
двоичного формата для входных объектных файлов, которые следуют за этой опцией
в командной строке. Даже если ld настроен для поддержки альтернативных форматов
объектных файлов, вам обычно не нужно это указывать, поскольку ld должен быть
настроен для ожидания формата ввода по умолчанию, который является наиболее
обычным на каждой машине. input-format — это строка текста, название
конкретного формата, поддерживаемого библиотеками BFD. (Вы можете перечислить
доступные двоичные форматы с помощью objdump -i.)
Вы можете захотеть использовать эту опцию, если связываете файлы с необычным
двоичным форматом. Вы также можете использовать -b для явного переключения
форматов (при связывании объектных файлов разных форматов), включив -b input-format
перед каждой группой объектных файлов в определённом формате.
Формат по умолчанию берётся из переменной окружения "GNUTARGET".
Вы также можете определить формат ввода из скрипта, используя команду "TARGET";
-c MRI-commandfile
--mri-script=MRI-commandfile
Для совместимости со связывателями, производимыми MRI, ld принимает скрипты,
написанные на альтернативном, ограниченном языке команд, описанном в разделе
MRI Compatible Script Files документации GNU ld. Введите скрипты MRI с опцией -c;
используйте опцию -T для запуска скриптов связывателя, написанных на общем
языке команд ld. Если MRI-cmdfile не существует, ld ищет его в каталогах,
указанных любой опцией -L.
-d
-dc
-dp Эти три опции эквивалентны; несколько форм поддерживаются для совместимости
с другими связывателями. Они выделяют пространство для общих символов даже если
указан выходной файл с возможностью перераспределения (с -r). Команда скрипта
"FORCE_COMMON_ALLOCATION" имеет тот же эффект.
--depaudit AUDITLIB
-P AUDITLIB
Добавляет AUDITLIB в запись "DT_DEPAUDIT" раздела динамических ссылок. AUDITLIB
не проверяется на существование, и она не будет использовать DT_SONAME, указанное
в библиотеке. Если указано несколько раз, "DT_DEPAUDIT" будет содержать список
интерфейсов аудита, разделённый двоеточиями. Эта опция осмысленна только на
платформах ELF, поддерживающих интерфейс rtld-audit. Опция -P предоставлена
для совместимости с Solaris.
--enable-linker-version
Включает директиву "LINKER_VERSION" в скрипте связывателя, описанную в Output
Section Data. Если эта директива используется в скрипте связывателя и эта опция
включена, то строка, содержащая версию связывателя, будет вставлена в текущей точке.
Замечание — положение этой опции в командной строке связывателя значимо. Она
повлияет только на скрипты связывателя, которые следуют за ней в командной строке,
или которые встроены в связыватель.
--disable-linker-version
Отключает директиву "LINKER_VERSION" в скрипте связывателя, так чтобы она
не вставляла строку версии. Это значение по умолчанию.
--enable-non-contiguous-regions
Эта опция предотвращает генерацию ошибки, если входной раздел не помещается
в соответствующий выходной раздел. Связыватель попытается выделить входной
раздел для последующих соответствующих выходных разделов и генерирует ошибку
только если ни один выходной раздел не достаточно велик. Это полезно, когда
доступны несколько неконтинуальных регионов памяти и входной раздел не требует
конкретного. Порядок оценки входных разделов не изменяется, например:
MEMORY {
MEM1 (rwx) : ORIGIN = 0x1000, LENGTH = 0x14
MEM2 (rwx) : ORIGIN = 0x1000, LENGTH = 0x40
MEM3 (rwx) : ORIGIN = 0x2000, LENGTH = 0x40
}
SECTIONS {
mem1 : { *(.data.*); } > MEM1
mem2 : { *(.data.*); } > MEM2
mem3 : { *(.data.*); } > MEM3
}
с входными разделами:
.data.1: размер 8
.data.2: размер 0x10
.data.3: размер 4
результатом является .data.1, назначенный mem1, и .data.2 и .data.3
назначенные mem2, несмотря на то, что .data.3 поместился бы в mem3.
Эта опция несовместима с инструкциями INSERT, поскольку она изменяет способ
отображения входных разделов на выходные разделы.
--enable-non-contiguous-regions-warnings
Эта опция включает предупреждения, когда "--enable-non-contiguous-regions"
позволяет потенциально неожиданные совпадения в отображении разделов, что может
привести к тихому отбрасыванию раздела вместо ошибки, поскольку он не помещается
в какой-либо выходной регион.
-e entry
--entry=entry
Использовать entry как явный символ для начала выполнения вашей программы,
вместо точки входа по умолчанию. Если символ с именем entry отсутствует,
связыватель попытается разобрать entry как число и использовать это как адрес
входа (число будет интерпретировано в базе 10; вы можете использовать ведущий
0x для базы 16 или ведущий 0 для базы 8).
--exclude-libs lib,lib,...
Указывает список архивных библиотек, из которых символы не должны автоматически
экспортироваться. Имена библиотек могут быть разделены запятыми или двоеточиями.
Указание "--exclude-libs ALL" исключает символы во всех архивных библиотеках
из автоматической экспорта. Эта опция доступна только для целевой платформы i386 PE
связывателя и для целевых платформ ELF. Для i386 PE символы, явно перечисленные
в файле .def, всё равно экспортируются, независимо от этой опции. Для целевых
платформ ELF символы, затронутые этой опцией, будут обработаны как скрытые.
--exclude-modules-for-implib module,module,...
Указывает список объектных файлов или членов архивов, из которых символы не должны
автоматически экспортироваться, но которые должны быть скопированы целиком
в генерируемую импортную библиотеку во время связывания. Имена модулей могут быть
разделены запятыми или двоеточиями и должны точно соответствовать именам файлов,
используемым ld для открытия файлов; для членов архивов это просто имя члена,
но для объектных файлов указанное имя должно включать и точно соответствовать
любому пути, использованному для указания входного файла в командной строке
связывателя. Эта опция доступна только для целевой платформы i386 PE связывателя.
Символы, явно перечисленные в файле .def, всё равно экспортируются, независимо
от этой опции.
-E
--export-dynamic
--no-export-dynamic
При создании динамически связываемого исполняемого файла опция -E или
--export-dynamic заставляет связыватель добавить все символы в таблицу динамических
символов. Таблица динамических символов — это набор символов, которые видны из
динамических объектов во время выполнения.
Если ни одна из этих опций не используется (или используется опция --no-export-dynamic
для восстановления поведения по умолчанию), таблица динамических символов обычно
содержит только те символы, которые ссылаются на какой-то динамический объект,
упомянутый в связывании.
Если вы используете "dlopen" для загрузки динамического объекта, который нуждается
в ссылках на символы, определённые программой, а не на какой-то другой динамический
объект, то вам, вероятно, нужно использовать эту опцию при связывании самой программы.
Вы также можете использовать динамический список для контроля, какие символы должны быть
добавлены в таблицу динамических символов, если формат вывода поддерживает это. См.
описание --dynamic-list.
Замечание — эта опция специфична для целевых платформ ELF. Целевые платформы PE
поддерживают похожую функцию для экспорта всех символов из DLL или EXE; см. описание
--export-all-symbols ниже.
--export-dynamic-symbol=glob
При создании динамически связываемого исполняемого файла символы, соответствующие
glob, будут добавлены в таблицу динамических символов. При создании разделяемой
библиотеки ссылки на символы, соответствующие glob, не будут привязаны к определениям
внутри разделяемой библиотеки. Эта опция не имеет эффекта при создании разделяемой
библиотеки и -Bsymbolic или --dynamic-list не указаны. Эта опция осмысленна только
на платформах ELF, поддерживающих разделяемые библиотеки.
--export-dynamic-symbol-list=file
Указать --export-dynamic-symbol для каждого шаблона в file. Формат файла такой же,
как узел версии без области видимости и имени узла. См. VERSION для дополнительной
информации.
-EB Связывать объектные файлы с большим порядком эндианов. Это влияет на формат вывода по умолчанию.
-EL Связывать объектные файлы с малым порядком эндианов. Это влияет на формат вывода по умолчанию.
-f name
--auxiliary=name
При создании разделяемого объекта ELF установить внутреннее поле DT_AUXILIARY
в указанное name. Это сообщает динамическому связывателю, что таблица символов
разделяемого объекта должна использоваться как вспомогательный фильтр для таблицы
символов разделяемого объекта name.
Если позже вы свяжите программу с этим объектом-фильтром, то при запуске программы
динамический связыватель увидит поле DT_AUXILIARY. Если динамический связыватель
разрешит какие-либо символы из объекта-фильтра, он сначала проверит, есть ли
определение в разделяемом объекте name. Если оно есть, оно будет использовано вместо
определения в объекте-фильтре. Разделяемый объект name необязательно существует.
Таким образом, разделяемый объект name может использоваться для предоставления
альтернативной реализации определённых функций, возможно, для отладки или для
производительности, специфичной для машины.
Эта опция может быть указана несколько раз. Записи DT_AUXILIARY будут созданы
в порядке, в котором они появляются в командной строке.
-F name
--filter=name
При создании разделяемого объекта ELF установить внутреннее поле DT_FILTER
в указанное name. Это сообщает динамическому связывателю, что таблица символов
разделяемого объекта, который создаётся, должна использоваться как фильтр для
таблицы символов разделяемого объекта name.
Если позже вы свяжите программу с этим объектом-фильтром, то при запуске программы
динамический связыватель увидит поле DT_FILTER. Динамический связыватель будет
разрешать символы в соответствии с таблицей символов объекта-фильтра, как обычно,
но на самом деле свяжет с определениями, найденными в разделяемом объекте name.
Таким образом, объект-фильтр может использоваться для выбора подмножества символов,
предоставляемых объектом name.
Некоторые старые связыватели использовали опцию -F на протяжении всей цепочки
компиляции для указания формата объектного файла как для входных, так и для
выходных объектных файлов. Связыватель GNU использует другие механизмы для этой
цели: опции -b, --format, --oformat, команду "TARGET" в скриптах связывателя
и переменную окружения "GNUTARGET". Связыватель GNU игнорирует опцию -F, если
не создаётся разделяемый объект ELF.
-fini=name
При создании исполняемого файла ELF или разделяемого объекта вызвать NAME при
выгрузке исполняемого файла или разделяемого объекта, установив DT_FINI на адрес
функции. По умолчанию связыватель использует "_fini" как функцию для вызова.
-g Игнорируется. Предоставлено для совместимости с другими инструментами.
-G value
--gpsize=value
Установить максимальный размер объектов, оптимизируемых с использованием регистра
GP, в size. Это осмысленно только для форматов объектных файлов, таких как MIPS ELF,
которые поддерживают размещение больших и малых объектов в разных разделах. Это
игнорируется для других форматов объектных файлов.
-h name
-soname=name
При создании разделяемого объекта ELF установить внутреннее поле DT_SONAME
в указанное name. Когда исполняемый файл связывается с разделяемым объектом,
у которого есть поле DT_SONAME, то при запуске исполняемого файла динамический
связыватель попытается загрузить разделяемый объект, указанный в поле DT_SONAME,
а не использовать имя файла, данное связывателю.
-i Выполнить инкрементальное связывание (то же, что и опция -r).
-init=name
При создании исполняемого файла ELF или разделяемого объекта вызвать NAME при
загрузке исполняемого файла или разделяемого объекта, установив DT_INIT на адрес
функции. По умолчанию связыватель использует "_init" как функцию для вызова.
-l namespec
--library=namespec
Добавить архив или объектный файл, указанный namespec, в список файлов для
связывания. Эта опция может использоваться любое количество раз. Если namespec
имеет форму :filename, ld будет искать в пути библиотек файл с именем filename,
в противном случае он будет искать файл с именем libnamespec.a.
На системах, поддерживающих разделяемые библиотеки, ld также может искать
файлы помимо libnamespec.a. Конкретно, на системах ELF и SunOS ld будет искать
в каталоге библиотеку с именем libnamespec.so перед поиском libnamespec.a.
(По конвенции, расширение ".so" указывает на разделяемую библиотеку.) Замечание,
что это поведение не применяется к :filename, которое всегда указывает файл
с именем filename.
Связыватель будет искать в архиве только один раз, в месте, где он указан
в командной строке. Если архив определяет символ, который был неопределённым
в каком-то объекте, который появился до архива в командной строке, связыватель
включит соответствующий файл(ы) из архива. Однако, неопределённый символ
в объекте, появляющемся позже в командной строке, не заставит связыватель
искать в архиве снова.
См. опцию -( для способа заставить связыватель искать в архивах несколько раз.
Вы можете перечислить один и тот же архив несколько раз в командной строке.
Этот тип поиска в архивах является стандартным для связывателей Unix. Однако,
если вы используете ld на AIX, обратите внимание, что это отличается от поведения
связывателя AIX.
-L searchdir
--library-path=searchdir
Добавить путь searchdir в список путей, которые ld будет искать архивные библиотеки
и скрипты управления ld. Вы можете использовать эту опцию любое количество раз.
Каталоги ищутся в порядке, в котором они указаны в командной строке. Каталоги,
указанные в командной строке, ищутся перед каталогами по умолчанию. Все опции -L
применяются ко всем опциям -l, независимо от порядка их появления. Опции -L не
влияют на то, как ld ищет скрипт связывателя, если не указана опция -T.
Если searchdir начинается с "=" или $SYSROOT, этот префикс будет заменён
префиксом sysroot, управляемым опцией --sysroot, или указанным при настройке
связывателя.
Набор путей поиска по умолчанию (без указания с -L) зависит от того, какую
эмуляцию использует ld, и в некоторых случаях также от того, как он был настроен.
Пути также могут быть указаны в скрипте связывателя с командой "SEARCH_DIR".
Каталоги, указанные таким образом, ищутся в точке, в которой скрипт связывателя
появляется в командной строке.
-m emulation
Эмулировать связыватель emulation. Вы можете перечислить доступные эмуляции
с опциями --verbose или -V.
Если опция -m не используется, эмуляция берётся из переменной окружения
"LDEMULATION", если она определена.
В противном случае, эмуляция по умолчанию зависит от того, как был настроен
связыватель.
--remap-inputs=pattern=filename
--remap-inputs-file=file
Эти опции позволяют изменить имена входных файлов перед тем, как связыватель
попытается открыть их. Опция --remap-inputs=foo.o=bar.o заставит любую попытку
загрузить файл с именем foo.o вместо этого попытаться загрузить файл с именем
bar.o. Шаблоны с подстановочными знаками допускаются в первом имени файла,
так что --remap-inputs=foo*.o=bar.o переименует любой входной файл, соответствующий
foo*.o, в bar.o.
Альтернативная форма опции --remap-inputs-file=filename позволяет читать
переименования из файла. Каждая строка в файле может содержать одно переименование.
Пустые строки игнорируются. Всё от символа хэша (#) до конца строки считается
комментарием и также игнорируется. Шаблон переименования может быть разделён
от имени файла пробелами или знаком равенства (=).
Опции могут быть указаны несколько раз. Их содержимое накапливается. Переименования
будут обработаны в порядке, в котором они появляются в командной строке, и если
они из файла, в порядке, в котором они появляются в файле. Если совпадение найдено,
дальнейшая проверка для этого имени файла не будет выполнена.
Если заменяемое имя файла — /dev/null или просто NUL, то переименование фактически
заставит игнорировать входной файл. Это удобный способ экспериментировать с удалением
входных файлов из сложной среды сборки.
Замечание — эта опция зависит от позиции и влияет только на имена файлов, которые
следуют за ней в командной строке. Таким образом:
ld foo.o --remap-inputs=foo.o=bar.o
Не окажет эффекта, в то время как:
ld --remap-inputs=foo.o=bar.o foo.o
Переименует входной файл foo.o в bar.o.
Замечание — эти опции также влияют на файлы, на которые ссылаются инструкции INPUT
в скриптах связывателя. Но поскольку скрипты связывателя обрабатываются после
всей командной строки, положение опций переименования в командной строке не значимо.
Если опция verbose включена, то любые совпадения, которые найдены, будут сообщены,
хотя опция verbose должна быть включена в командной строке до появления переименованных
имён файлов.
Если опции -Map или --print-map включены, то список переименований будет включён
в вывод карты.
-M
--print-map
Печатать карту связывания в стандартный вывод. Карта связывания предоставляет
информацию о связывании, включая следующее:
• Где объектные файлы отображаются в памяти.
• Как распределяются общие символы.
• Все члены архивов, включённые в связывание, с упоминанием символа, который
заставил включить член архива.
• Значения, присвоенные символам.
Замечание — символы, значения которых вычисляются выражением, которое включает
ссылку на предыдущее значение того же символа, могут не отображать правильный
результат в карте связывания. Это потому, что связыватель отбрасывает промежуточные
результаты и сохраняет только конечное значение выражения. В таких обстоятельствах
связыватель отобразит конечное значение в квадратных скобках. Таким образом, например,
скрипт связывателя, содержащий:
foo = 1
foo = foo * 4
foo = foo + 8
произведёт следующий вывод в карте связывания, если используется опция -M:
0x00000001 foo = 0x1
[0x0000000c] foo = (foo * 0x4)
[0x0000000c] foo = (foo + 0x8)
См. Expressions для дополнительной информации о выражениях в скриптах связывателя.
• Как объединяются свойства GNU.
Когда связыватель объединяет входные разделы .note.gnu.property в один выходной
раздел .note.gnu.property, некоторые свойства удаляются или обновляются. Эти действия
отображаются в карте связывания. Например:
Removed property 0xc0000002 to merge foo.o (0x1) and bar.o (not found)
Это указывает, что свойство 0xc0000002 удалено из вывода при объединении свойств
в foo.o, чьё свойство 0xc0000002 равно 0x1, и bar.o, в котором нет свойства
0xc0000002.
Updated property 0xc0010001 (0x1) to merge foo.o (0x1) and bar.o (0x1)
Это указывает, что значение свойства 0xc0010001 обновлено до 0x1 в выводе при
объединении свойств в foo.o, чьё свойство 0xc0010001 равно 0x1, и bar.o, чьё
свойство 0xc0010001 равно 0x1.
• На некоторых целевых платформах ELF список фиксаций, вставленных --relax.
foo.o: Adjusting branch at 0x00000008 towards "far" in section .text
Это указывает, что ветвление на 0x00000008 в foo.o, ориентированное на символ
"far" в разделе .text, было заменено на трамплин.
--print-map-discarded
--no-print-map-discarded
Печатать (или не печатать) список отброшенных и собранных мусором разделов
в карте связывания. Включено по умолчанию.
--print-map-locals
--no-print-map-locals
Печатать (или не печатать) локальные символы в карте связывания. Локальные
символы будут иметь текст (local), напечатанный перед их именем, и будут
перечислены после всех глобальных символов в данном разделе. Временные
локальные символы (обычно те, что начинаются с .L) не будут включены в вывод.
Отключено по умолчанию.
-n
--nmagic
Отключить выравнивание разделов по страницам и запретить связывание с
разделяемыми библиотеками. Если формат вывода поддерживает магические числа
в стиле Unix, пометить вывод как "NMAGIC".
-N
--omagic
Сделать разделы текста и данных читаемыми и записываемыми. Кроме того,
не выравнивать раздел данных по страницам и запретить связывание с
разделяемыми библиотеками. Если формат вывода поддерживает магические числа
в стиле Unix, пометить вывод как "OMAGIC". Замечание: Хотя записываемый
раздел текста разрешается для целевых платформ PE-COFF, это не соответствует
спецификации формата, опубликованной Microsoft.
--no-omagic
Эта опция отменяет большинство эффектов опции -N. Она устанавливает раздел
текста как читаемый, и заставляет раздел данных выравниваться по страницам.
Замечание — эта опция не включает связывание с разделяемыми библиотеками.
Используйте -Bdynamic для этого.
-o output
--output=output
Использовать output как имя для программы, произведённой ld; если эта опция
не указана, имя a.out используется по умолчанию. Команда скрипта "OUTPUT"
также может указать имя выходного файла.
Замечание — связыватель удалит выходной файл перед тем, как начать писать
в него. Он сделает это даже если выяснится, что связывание не может быть
завершено из-за ошибок.
Замечание — связыватель проверит, чтобы имя выходного файла не совпадало
с именем любого из входных файлов, но на этом всё. В частности, он не
пожалуется, если выходной файл может перезаписать исходный файл или какой-то
другой важный файл. Поэтому в системах сборки рекомендуется использовать
опцию -o как последнюю опцию в командной строке связывателя. Например, рассмотрите:
ld -o $(EXE) $(OBJS)
ld $(OBJS) -o $(EXE)
Если переменная EXE не определена по какой-то причине, первая версия командной
строки связывателя может закончиться удалением одного из объектных файлов
(первого в списке OBJS), в то время как вторая версия командной строки связывателя
сгенерирует сообщение об ошибке и ничего не удалит.
--dependency-file=depfile
Записать файл зависимостей в depfile. Этот файл содержит правило, подходящее
для "make", описывающее выходной файл и все входные файлы, которые были прочитаны
для его создания. Вывод похож на вывод компилятора с -M -MP. Замечание, что
нет опции вроде -MM компилятора, для исключения "системных файлов" (что не
является хорошо определённым понятием для связывателя, в отличие от "системных
заголовков" для компилятора). Таким образом, вывод от --dependency-file всегда
специфичен для точного состояния установки, где он был произведён, и не должен
копироваться в распространяемые файлы makefile без тщательной правки.
-O level
Если level — числовое значение больше нуля, ld оптимизирует вывод. Это может
занять значительно больше времени и поэтому, вероятно, должно быть включено
только для финального бинарника. В данный момент эта опция влияет только на
генерацию разделяемых библиотек ELF. Будущие выпуски связывателя могут больше
использовать эту опцию. Кроме того, в настоящее время нет разницы в поведении
связывателя для разных ненулевых значений этой опции. Опять же, это может измениться
в будущих выпусках.
-plugin name
Вовлечь плагин в процесс связывания. Параметр name — абсолютное имя файла
плагина. Обычно этот параметр автоматически добавляется компилятором при
использовании связывания во время оптимизации, но пользователи также могут
добавлять свои плагины, если захотят.
Замечание, что местоположение плагинов, происходящих от компилятора, отличается
от места, где программы ar, nm и ranlib ищут свои плагины. Чтобы эти команды
могли использовать плагин на основе компилятора, его сначала нужно скопировать
в каталог ${libdir}/bfd-plugins. Все плагины связывателя на основе gcc совместимы
назад, так что достаточно скопировать самый новый.
--push-state
--push-state позволяет сохранить текущее состояние флагов, управляющих обработкой
входных файлов, чтобы их можно было все восстановить одной соответствующей опцией
--pop-state.
Опции, которые охватываются: -Bdynamic, -Bstatic, -dn, -dy, -call_shared,
-non_shared, -static, -N, -n, --whole-archive, --no-whole-archive, -r, -Ur,
--copy-dt-needed-entries, --no-copy-dt-needed-entries, --as-needed,
--no-as-needed и -a.
Одним из назначений этой опции являются спецификации для pkg-config. При
использовании с опцией --libs все потенциально нужные библиотеки перечислены
и затем, возможно, связаны всё время. Лучше вернуть что-то вроде:
-Wl,--push-state,--as-needed -libone -libtwo -Wl,--pop-state
--pop-state
Отменяет эффект --push-state, восстанавливает предыдущие значения флагов,
управляющих обработкой входных файлов.
-q
--emit-relocs
Оставить разделы релокаций и их содержимое в полностью связанных исполняемых
файлах. Инструменты постобработки и оптимизации могут нуждаться в этой информации
для выполнения правильных модификаций исполняемых файлов. Это приводит к
большим исполняемым файлам.
Эта опция в настоящее время поддерживается только на платформах ELF.
--force-dynamic
Заставить выходной файл иметь динамические разделы. Эта опция специфична
для целевых платформ VxWorks.
-r
--relocatable
Генерировать выход с возможностью перераспределения — т.е. генерировать выходной
файл, который в свою очередь может служить входом для ld. Это часто называется
частичным связыванием. Как побочный эффект, в средах, поддерживающих стандартные
магические числа Unix, эта опция также устанавливает магическое число выходного
файла в "OMAGIC". Если эта опция не указана, производится абсолютный файл.
При связывании программ C++ эта опция не разрешит ссылки на конструкторы; для
этого используйте -Ur.
Когда входной файл не имеет того же формата, что и выходной файл, частичное
связывание поддерживается только если входной файл не содержит релокаций.
Разные форматы вывода могут иметь дополнительные ограничения; например, некоторые
форматы на основе "a.out" не поддерживают частичное связывание с входными файлами
в других форматах вообще.
Когда выход с возможностью перераспределения содержит как содержимое, требующее
оптимизации во время связывания (LTO), так и содержимое, не требующее LTO, будет
создан раздел .gnu_object_only, содержащий объектный файл с возможностью
перераспределения, как если бы -r применялась ко всем перераспределяемым входам,
не требующим LTO. При обработке входного файла с возможностью перераспределения
с разделом .gnu_object_only связыватель извлечёт раздел .gnu_object_only как
отдельный вход.
Замечание, что поскольку -r группирует некоторые разделы из разных входных файлов
вместе, это может негативно повлиять на размер кода и локальность в финальном
исполняемом файле или разделяемой библиотеке.
Эта опция делает то же самое, что и -i.
-R filename
--just-symbols=filename
Читать имена символов и их адреса из filename, но не перераспределять его
или не включать в вывод. Это позволяет вашему выходному файлу ссылаться символически
на абсолютные расположения памяти, определённые в других программах. Вы можете
использовать эту опцию несколько раз.
Для совместимости с другими связывателями ELF, если опция -R следует за именем
каталога, а не именем файла, она обрабатывается как опция -rpath.
--rosegment
--no-rosegment
Пытаться обеспечить, чтобы был создан только один читаемый, не-кодовый сегмент.
Полезно только в сочетании с опцией -z separate-code. Результирующие бинарники
должны быть меньше, чем если бы использовалась только -z separate-code. Без этой
опции, или если указана --no-rosegment, опция -z separate-code создаст два читаемых
сегмента, один перед сегментом кода и один после него.
Имена опций вводящие в заблуждение, но они выбраны для того, чтобы связыватель
был совместим с связывателями LLD и GOLD.
Эти опции поддерживаются только на целевых платформах ELF.
-s
--strip-all
Убрать всю информацию о символах из выходного файла.
-S
--strip-debug
Убрать информацию о символах отладчика (но не все символы) из выходного файла.
--strip-discarded
--no-strip-discarded
Убрать (или не убирать) глобальные символы, определённые в отброшенных разделах.
Включено по умолчанию.
-plugin-save-temps
Хранить промежуточные файлы плагина "временно" постоянно.
-t
--trace
Печатать имена входных файлов по мере обработки ld. Если -t указана дважды,
то члены внутри архивов также печатаются. Вывод -t полезен для генерации списка
всех объектных файлов и скриптов, участвующих в связывании, например, при упаковке
файлов для отчёта об ошибке связывателя.
-T scriptfile
--script=scriptfile
Использовать scriptfile как скрипт связывателя. Этот скрипт заменяет скрипт
связывателя ld по умолчанию (а не добавляет к нему), если скрипт не содержит
"INSERT", поэтому commandfile должен указывать всё необходимое для описания
выходного файла.
Если scriptfile не существует в текущем каталоге, "ld" ищет его в каталогах,
указанных любой предыдущей опцией -L.
Опции командной строки, которые появляются перед опцией -T, могут повлиять
на скрипт, но опции командной строки, которые появляются после неё, не влияют.
Несколько опций -T будут накапливаться, если они дополняют текущий скрипт,
в противном случае будет использована последняя, не дополняющая, опция -T.
Существуют и другие способы указания скриптов связывателя. См.
-dT scriptfile
--default-script=scriptfile
Использовать scriptfile как скрипт связывателя по умолчанию.
Эта опция похожа на опцию --script, за исключением того, что обработка скрипта
откладывается до тех пор, пока не будет обработана вся остальная командная строка.
Это позволяет опциям, размещённым после опции --default-script в командной строке,
влиять на поведение скрипта связывателя, что может быть важно, когда командная
строка связывателя не может быть напрямую контролируема пользователем. (Например,
потому что командная строка строится другим инструментом, таким как gcc).
-u symbol
--undefined=symbol
Заставить symbol войти в выходной файл как неопределённый символ. Это может,
например, вызвать связывание дополнительных модулей из стандартных библиотек.
-u может быть повторено с разными аргументами опций для ввода дополнительных
неопределённых символов. Эта опция эквивалентна команде скрипта "EXTERN".
Если эта опция используется для принудительного включения дополнительных модулей
в связывание, и если это ошибка, что символ остаётся неопределённым, то следует
использовать опцию --require-defined.
--require-defined=symbol
Требовать, чтобы symbol был определён в выходном файле. Эта опция такая же,
как опция --undefined, за исключением того, что если symbol не определён
в выходном файле, связыватель выдаст ошибку и выйдет. Тот же эффект можно достичь
в скрипте связывателя, используя "EXTERN", "ASSERT" и "DEFINED" вместе.
Эта опция может использоваться несколько раз для требования дополнительных символов.
-Ur Для программ, которые не используют конструкторы или деструкторы, или для
систем на основе ELF эта опция эквивалентна -r: она генерирует выход с
возможностью перераспределения — т.е. выходной файл, который в свою очередь
может служить входом для ld. Для других бинарников однако опция -Ur похожа
на -r, но она также разрешает ссылки на конструкторы и деструкторы.
Для тех систем, где -r и -Ur ведут себя по-разному, не работает использование
-Ur на файлах, которые сами были связаны с -Ur; как только таблица конструкторов
построена, её нельзя добавить. Используйте -Ur только для последнего частичного
связывания, а -r для остальных.
--orphan-handling=MODE
Контролировать, как обрабатываются сиротские разделы. Сиротский раздел —
это тот, который не указан явно в скрипте связывателя.
MODE может иметь одно из следующих значений:
"place"
Сиротские разделы размещаются в подходящем выходном разделе в соответствии
со стратегией, описанной в Orphan Sections. Опция --unique также влияет на
то, как размещаются разделы.
"discard"
Все сиротские разделы отбрасываются, размещая их в разделе /DISCARD/.
"warn"
Связыватель размещает сиротский раздел как для "place" и также выдаёт
предупреждение.
"error"
Связыватель выйдет с ошибкой, если найдён какой-либо сиротский раздел.
Значение по умолчанию, если --orphan-handling не указано, — "place".
--unique[=SECTION]
Создаёт отдельный выходной раздел для каждого входного раздела, соответствующего
SECTION, или, если необязательный аргумент шаблона SECTION отсутствует, для
каждого сиротского входного раздела. Сиротский раздел — это тот, который не
указан явно в скрипте связывателя. Вы можете использовать эту опцию несколько
раз в командной строке; она предотвращает нормальное слияние входных разделов
с одинаковыми именами, переопределяя назначения выходных разделов в скрипте
связывателя.
-v
--version
-V Показать номер версии ld. Опция -V также перечисляет поддерживаемые эмуляции.
См. также описание --enable-linker-version в Options,,Command-line Options,
которая может использоваться для вставки строки версии связывателя в бинарник.
-x
--discard-all
Удалить все локальные символы.
-X
--discard-locals
Удалить все временные локальные символы. (Эти символы начинаются с префиксов
локальных меток, специфичных для системы, обычно .L для систем ELF или L для
традиционных систем a.out.)
-y symbol
--trace-symbol=symbol
Печатать имя каждого связанного файла, в котором появляется symbol. Эта опция
может быть указана любое количество раз. На многих системах необходимо предшествовать
подчёркиванием.
Эта опция полезна, когда у вас есть неопределённый символ в связывании, но вы
не знаете, откуда идёт ссылка.
-Y path
Добавить path в путь поиска библиотек по умолчанию. Эта опция существует
для совместимости с Solaris.
-z keyword
Распознаваемые keyword:
call-nop=prefix-addr
call-nop=suffix-nop
call-nop=prefix-byte
call-nop=suffix-byte
Указать 1-байтовую "NOP" подкладку при преобразовании косвенного вызова
в локально определённую функцию, foo, через её слот GOT. call-nop=prefix-addr
генерирует "0x67 call foo". call-nop=suffix-nop генерирует "call foo 0x90".
call-nop=prefix-byte генерирует "byte call foo". call-nop=suffix-byte
генерирует "call foo byte". Поддерживается для i386 и x86_64.
cet-report=none
cet-report=warning
cet-report=error
Указать, как сообщать об отсутствующих GNU_PROPERTY_X86_FEATURE_1_IBT
и GNU_PROPERTY_X86_FEATURE_1_SHSTK свойствах во входном разделе
.note.gnu.property. cet-report=none, что является значением по умолчанию,
заставит связыватель не сообщать об отсутствующих свойствах во входных файлах.
cet-report=warning заставит связыватель выдать предупреждение об отсутствующих
свойствах во входных файлах. cet-report=error заставит связыватель выдать
ошибку об отсутствующих свойствах во входных файлах. Замечание, что ibt
отключит отчёт об отсутствующем свойстве GNU_PROPERTY_X86_FEATURE_1_IBT,
а shstk отключит отчёт об отсутствующем свойстве GNU_PROPERTY_X86_FEATURE_1_SHSTK.
Поддерживается для Linux/i386 и Linux/x86_64.
combreloc
nocombreloc
Объединить несколько разделов динамических релокаций и отсортировать для
улучшения кэширования поиска динамических символов. Не делать это, если nocombreloc.
common
nocommon
Генерировать общие символы с типом STT_COMMON во время связывания с
возможностью перераспределения. Использовать тип STT_OBJECT, если nocommon.
common-page-size=value
Установить размер страницы, наиболее часто используемый, в value. Расположение
изображения памяти будет оптимизировано для минимизации страниц памяти, если
система использует страницы этого размера.
defs
Сообщать о неразрешённых ссылках на символы из обычных объектных файлов.
Это делается даже если связыватель создаёт несимволическую разделяемую библиотеку.
Эта опция — обратная -z undefs.
dynamic-undefined-weak
nodynamic-undefined-weak
Сделать неопределённые слабые символы динамическими при построении динамического
объекта, если на них ссылаются из обычного объектного файла и они не вынуждены
быть локальными из-за видимости символа или версионности. Не делать их динамическими,
если nodynamic-undefined-weak. Если ни одна опция не указана, цель может по умолчанию
использовать любую опцию, или сделать другой выбор неопределённых слабых символов
динамическими. Не все цели поддерживают эти опции.
execstack
Помечает объект как требующий исполняемого стека.
global
Эта опция осмысленна только при построении разделяемого объекта. Она делает
символы, определённые в этом разделяемом объекте, доступными для разрешения
символов в последующих загружаемых библиотеках.
globalaudit
Эта опция осмысленна только при построении динамического исполняемого файла.
Эта опция помечает исполняемый файл как требующий глобального аудита путём
установки бита "DF_1_GLOBAUDIT" в теге "DT_FLAGS_1". Глобальный аудит требует,
чтобы любая библиотека аудита, определённая опциями --depaudit или -P, выполнялась
для всех динамических объектов, загружаемых приложением.
ibtplt
Генерировать записи PLT, включённые для отслеживания косвенных ветвлений Intel (IBT).
Поддерживается для Linux/i386 и Linux/x86_64.
ibt Генерировать GNU_PROPERTY_X86_FEATURE_1_IBT в разделе .note.gnu.property
для указания совместимости с IBT. Это также подразумевает ibtplt. Поддерживается
для Linux/i386 и Linux/x86_64.
indirect-extern-access
noindirect-extern-access
Генерировать GNU_PROPERTY_1_NEEDED_INDIRECT_EXTERN_ACCESS в разделе
.note.gnu.property для указания, что объектный файл требует канонических
указателей функций и не может использоваться с релокацией копирования.
Эта опция также подразумевает noextern-protected-data и nocopyreloc.
Поддерживается для i386 и x86-64.
noindirect-extern-access удаляет GNU_PROPERTY_1_NEEDED_INDIRECT_EXTERN_ACCESS
из раздела .note.gnu.property.
initfirst
Эта опция осмысленна только при построении разделяемого объекта. Она помечает
объект так, что его инициализация во время выполнения произойдёт до инициализации
любого другого объекта, загруженного в процесс в то же время. Аналогично,
финализация во время выполнения объекта произойдёт после финализации любого
другого объекта.
interpose
Указать, что динамический загрузчик должен изменить порядок поиска символов,
так чтобы символы в этой разделяемой библиотеке вставлялись во все другие
разделяемые библиотеки, не отмеченные таким образом.
unique
nounique
При генерации разделяемой библиотеки или другого динамически загружаемого
объекта ELF пометить его как такой, который по умолчанию должен загружаться
только один раз и только в основном пространстве имён (при использовании "dlmopen").
Это в первую очередь используется для пометки фундаментальных библиотек, таких
как libc, libpthread и т.д., которые обычно не работают правильно, если они
не являются единственными экземплярами себя. Это поведение может быть переопределено
вызывающим "dlmopen" и не применяется к некоторым механизмам загрузки (таким
как библиотеки аудита).
lam-u48
Генерировать GNU_PROPERTY_X86_FEATURE_1_LAM_U48 в разделе .note.gnu.property
для указания совместимости с Intel LAM_U48. Поддерживается для Linux/x86_64.
lam-u57
Генерировать GNU_PROPERTY_X86_FEATURE_1_LAM_U57 в разделе .note.gnu.property
для указания совместимости с Intel LAM_U57. Поддерживается для Linux/x86_64.
lam-u48-report=none
lam-u48-report=warning
lam-u48-report=error
Указать, как сообщать об отсутствующем свойстве GNU_PROPERTY_X86_FEATURE_1_LAM_U48
во входном разделе .note.gnu.property. lam-u48-report=none, что является
значением по умолчанию, заставит связыватель не сообщать об отсутствующих
свойствах во входных файлах. lam-u48-report=warning заставит связыватель выдать
предупреждение об отсутствующих свойствах во входных файлах. lam-u48-report=error
заставит связыватель выдать ошибку об отсутствующих свойствах во входных файлах.
Поддерживается для Linux/x86_64.
lam-u57-report=none
lam-u57-report=warning
lam-u57-report=error
Указать, как сообщать об отсутствующем свойстве GNU_PROPERTY_X86_FEATURE_1_LAM_U57
во входном разделе .note.gnu.property. lam-u57-report=none, что является
значением по умолчанию, заставит связыватель не сообщать об отсутствующих
свойствах во входных файлах. lam-u57-report=warning заставит связыватель выдать
предупреждение об отсутствующих свойствах во входных файлах. lam-u57-report=error
заставит связыватель выдать ошибку об отсутствующих свойствах во входных файлах.
Поддерживается для Linux/x86_64.
lam-report=none
lam-report=warning
lam-report=error
Указать, как сообщать об отсутствующих свойствах GNU_PROPERTY_X86_FEATURE_1_LAM_U48
и GNU_PROPERTY_X86_FEATURE_1_LAM_U57 во входном разделе .note.gnu.property.
lam-report=none, что является значением по умолчанию, заставит связыватель не
сообщать об отсутствующих свойствах во входных файлах. lam-report=warning заставит
связыватель выдать предупреждение об отсутствующих свойствах во входных файлах.
lam-report=error заставит связыватель выдать ошибку об отсутствующих свойствах
во входных файлах. Поддерживается для Linux/x86_64.
lazy
При генерации исполняемого файла или разделяемой библиотеки пометить его,
чтобы динамический связыватель откладывал разрешение вызовов функций до момента,
когда функция вызывается (ленивая привязка), а не во время загрузки. Ленивая
привязка — это значение по умолчанию.
loadfltr
Указать, что фильтры объекта должны обрабатываться немедленно во время выполнения.
max-page-size=value
Установить максимальный поддерживаемый размер страницы памяти в value.
mark-plt
nomark-plt
Помечать записи PLT динамическими тегами, DT_X86_64_PLT, DT_X86_64_PLTSZ
и DT_X86_64_PLTENT. Поскольку эта опция сохраняет ненулевое значение в поле
r_addend релокаций R_X86_64_JUMP_SLOT, результирующие исполняемые файлы и
разделяемые библиотеки несовместимы с динамическими связывателями, такими как
те в старых версиях glibc без изменений для игнорирования r_addend в
R_X86_64_GLOB_DAT и R_X86_64_JUMP_SLOT релокациях, которые не игнорируют поле
r_addend релокаций R_X86_64_JUMP_SLOT. Поддерживается для x86_64.
muldefs
Разрешить несколько определений.
nocopyreloc
Отключить переменные .dynbss, генерируемые связывателем, используемые вместо
переменных, определённых в разделяемых библиотеках. Может привести к динамическим
релокациям текста.
nodefaultlib
Указать, что поиск зависимостей этого объекта динамическим загрузчиком должен
игнорировать любые пути поиска библиотек по умолчанию.
nodelete
Указать, что объект не должен выгружаться во время выполнения.
nodlopen
Указать, что объект недоступен для "dlopen".
nodump
Указать, что объект не может быть выгружен "dldump".
noexecstack
Помечает объект как не требующий исполняемого стека.
noextern-protected-data
Не обрабатывать защищённые данные как внешние при построении разделяемой
библиотеки. Эта опция переопределяет значение по умолчанию бэкенда связывателя.
Она может использоваться для обхода неправильных релокаций на защищённые
данные символы, генерируемые компилятором. Обновления защищённых данных
символов другим модулем не видны в результирующей разделяемой библиотеке.
Поддерживается для i386 и x86-64.
noreloc-overflow
Отключить проверку переполнения релокаций. Это может использоваться для отключения
проверки переполнения релокаций, если не будет динамического переполнения релокаций
во время выполнения. Поддерживается для x86_64.
memory-seal
nomemory-seal
Инструктировать исполняемый файл или разделяемую библиотеку, что все сегменты
PT_LOAD должны быть запечатаны для предотвращения дальнейшей манипуляции (например,
изменения флагов защиты, размера сегмента или удаления отображения). Это мера
повышения безопасности, требующая поддержки системы. Это генерирует GNU_PROPERTY_MEMORY_SEAL
в разделе .note.gnu.property.
now Когда генерируется исполняемый файл или разделяемая библиотека, пометить его,
чтобы динамический связыватель разрешал все символы при запуске программы или
при загрузке разделяемой библиотеки dlopen, вместо того чтобы откладывать
разрешение вызовов функций до момента первого вызова.
origin
Указать, что объект требует обработки $ORIGIN в путях.
pack-relative-relocs
nopack-relative-relocs
Генерировать компактные относительные релокации в исполняемых файлах с
позиционно-независимым кодом и разделяемых библиотеках. Это добавляет записи
"DT_RELR", "DT_RELRSZ" и "DT_RELRENT" в динамический раздел. Игнорируется при
построении позиционно-зависимого исполняемого файла и вывода с возможностью
перераспределения. nopack-relative-relocs — значение по умолчанию, которое
отключает компактные относительные релокации. Когда связывается с библиотекой
GNU C, добавляется зависимость версии символа GLIBC_ABI_DT_RELR от разделяемой
библиотеки C. Поддерживается для i386 и x86-64.
relro
norelro
Создать заголовок сегмента ELF "PT_GNU_RELRO". Это указывает сегмент памяти,
который должен быть сделан только для чтения после релокации, если это поддерживается.
Указание common-page-size меньшего, чем размер страницы системы, сделает эту защиту
неэффективной. Не создавать заголовок сегмента ELF "PT_GNU_RELRO", если указана norelro.
report-relative-reloc
Сообщать о динамических относительных релокациях, генерируемых связывателем.
Поддерживается для Linux/i386 и Linux/x86_64.
sectionheader
nosectionheader
Генерировать заголовок раздела. Не генерировать заголовок раздела, если указана
nosectionheader. sectionheader — значение по умолчанию.
separate-code
noseparate-code
Создать отдельный заголовок сегмента "PT_LOAD" для кода в объекте. Это указывает
сегмент памяти, который должен содержать только инструкции и должен быть полностью
разнесён по страницам от любых других данных. Не создавать отдельный заголовок
сегмента "PT_LOAD" для кода, если указана noseparate-code.
shstk
Генерировать GNU_PROPERTY_X86_FEATURE_1_SHSTK в разделе .note.gnu.property
для указания совместимости с Intel Shadow Stack. Поддерживается для Linux/i386
и Linux/x86_64.
stack-size=value
Указать размер стека для сегмента ELF "PT_GNU_STACK". Указание нуля переопределит
создание любого сегмента "PT_GNU_STACK" с ненулевым размером по умолчанию.
start-stop-gc
nostart-stop-gc
Когда --gc-sections действует, ссылка из сохранённого раздела на "__start_SECNAME"
или "__stop_SECNAME" заставляет все входные разделы с именем "SECNAME" также
сохраниться, если "SECNAME" представимо как идентификатор C и либо "__start_SECNAME",
либо "__stop_SECNAME" синтезировано связывателем. -z start-stop-gc отключает
этот эффект, позволяя разделам быть собранными мусором, как будто специальные
синтезированные символы не определены. -z start-stop-gc не влияет на определение
"__start_SECNAME" или "__stop_SECNAME" в объектном файле или скрипте связывателя.
Такое определение предотвратит предоставление связывателем синтезированного
"__start_SECNAME" или "__stop_SECNAME" соответственно, и поэтому специальное
обращение сборщиком мусора для этих ссылок.
start-stop-visibility=value
Указать видимость ELF-символа для синтезированных символов "__start_SECNAME"
и "__stop_SECNAME". value должно быть точно default, internal, hidden или protected.
Если опция -z start-stop-visibility не указана, используется protected для
совместимости с исторической практикой. Однако, настоятельно рекомендуется
использовать -z start-stop-visibility=hidden в новых программах и разделяемых
библиотеках, чтобы эти символы не экспортировались между разделяемыми объектами,
что обычно не intended.
text
notext
textoff
Сообщать об ошибке, если установлен DT_TEXTREL, т.е. если позиционно-независимый
или разделяемый объект имеет динамические релокации в разделах только для чтения.
Не сообщать об ошибке, если указана notext или textoff.
undefs
Не сообщать о неразрешённых ссылках на символы из обычных объектных файлов,
как при создании исполняемого файла, так и при создании разделяемой библиотеки.
Эта опция — обратная -z defs.
unique-symbol
nounique-symbol
Избегать дублированных имён локальных символов в строковой таблице символов.
Добавить ".number" к дублированным именам локальных символов, если указана
unique-symbol. nounique-symbol — значение по умолчанию.
x86-64-baseline
x86-64-v2
x86-64-v3
x86-64-v4
Указать уровень ISA x86-64, необходимый в разделе .note.gnu.property. x86-64-baseline
генерирует "GNU_PROPERTY_X86_ISA_1_BASELINE". x86-64-v2 генерирует "GNU_PROPERTY_X86_ISA_1_V2".
x86-64-v3 генерирует "GNU_PROPERTY_X86_ISA_1_V3". x86-64-v4 генерирует "GNU_PROPERTY_X86_ISA_1_V4".
Поддерживается для Linux/i386 и Linux/x86_64.
isa-level-report=none
isa-level-report=all
isa-level-report=needed
isa-level-report=used
Указать, как сообщать об уровнях ISA x86-64 во входных файлах с возможностью
перераспределения. isa-level-report=none, что является значением по умолчанию,
заставит связыватель не сообщать об уровнях ISA x86-64 во входных файлах.
isa-level-report=all заставит связыватель сообщать о нужных и используемых
уровнях ISA x86-64 во входных файлах. isa-level-report=needed заставит
связыватель сообщать о нужных уровнях ISA x86-64 во входных файлах. isa-level-report=used
заставит связыватель сообщать об используемых уровнях ISA x86-64 во входных файлах.
Поддерживается для Linux/i386 и Linux/x86_64.
Другие keyword игнорируются для совместимости с Solaris.
-( archives -)
--start-group archives --end-group
archives должны быть списком архивных файлов. Они могут быть либо явными
именами файлов, либо опциями -l.
Указанные архивы ищутся повторно, пока не будут созданы новые неопределённые
ссылки. Нормально архив ищется только один раз в порядке, в котором он указан
в командной строке. Если символ в этом архиве нужен для разрешения неопределённого
символа, на который ссылается объект в архиве, который появляется позже в
командной строке, связыватель не сможет разрешить эту ссылку. Группируя архивы,
они все будут искаться повторно, пока не будут разрешены все возможные ссылки.
Использование этой опции имеет значительную стоимость производительности. Лучше
использовать её только при неизбежных циклических ссылках между двумя или более
архивами.
--accept-unknown-input-arch
--no-accept-unknown-input-arch
Говорит связывателю принимать входные файлы, архитектуру которых нельзя распознать.
Предполагается, что пользователь знает, что делает, и намеренно хочет связать
эти неизвестные входные файлы. Это было поведением связывателя по умолчанию до
выпуска 2.14. Поведение по умолчанию с выпуска 2.14 onward — отвергать такие
входные файлы, и опция --accept-unknown-input-arch добавлена для восстановления
старого поведения.
--as-needed
--no-as-needed
Эта опция влияет на теги ELF DT_NEEDED для динамических библиотек, упомянутых
в командной строке после опции --as-needed. Нормально связыватель добавит тег
DT_NEEDED для каждой динамической библиотеки, упомянутой в командной строке,
независимо от того, нужна она или нет. --as-needed заставляет тег DT_NEEDED
генерироваться только для библиотеки, которая на этом этапе связывания удовлетворяет
неслабой неопределённой ссылке на символ из обычного объектного файла или, если
библиотека не найдена в списках DT_NEEDED других нужных библиотек, неслабой
неопределённой ссылке на символ из другой нужной динамической библиотеки. Объектные
файлы или библиотеки, появляющиеся в командной строке после библиотеки в вопросе,
не влияют на то, считается ли библиотека нужной. Это похоже на правила извлечения
объектных файлов из архивов. --no-as-needed восстанавливает поведение по умолчанию.
Замечание: На системах на основе Linux опция --as-needed также влияет на поведение
опций --rpath и --rpath-link. См. описание --rpath-link для дополнительной информации.
--add-needed
--no-add-needed
Эти две опции устарели из-за схожести их имён с опциями --as-needed и
--no-as-needed. Они заменены на --copy-dt-needed-entries и --no-copy-dt-needed-entries.
-assert keyword
Эта опция игнорируется для совместимости с SunOS.
-Bdynamic
-dy
-call_shared
Связываться с динамическими библиотеками. Это осмысленно только на платформах,
поддерживающих разделяемые библиотеки. Эта опция обычно является значением по
умолчанию на таких платформах. Разные варианты этой опции предназначены для
совместимости с различными системами. Вы можете использовать эту опцию несколько
раз в командной строке: она влияет на поиск библиотек для опций -l, которые следуют
за ней.
-Bgroup
Установить флаг "DF_1_GROUP" в записи "DT_FLAGS_1" в динамическом разделе.
Это заставит рантайм-связыватель выполнять поиск в этом объекте и его зависимостях
только внутри группы. Подразумевается --unresolved-symbols=report-all. Эта опция
осмысленна только на платформах ELF, поддерживающих разделяемые библиотеки.
-Bstatic
-dn
-non_shared
-static
Не связываться с разделяемыми библиотеками. Это осмысленно только на платформах,
поддерживающих разделяемые библиотеки. Разные варианты этой опции предназначены
для совместимости с различными системами. Вы можете использовать эту опцию несколько
раз в командной строке: она влияет на поиск библиотек для опций -l, которые следуют
за ней. Эта опция также подразумевает --unresolved-symbols=report-all. Эта опция
может использоваться с -shared. В этом случае создаётся разделяемая библиотека,
но все внешние ссылки библиотеки должны быть разрешены путём включения записей
из статических библиотек.
-Bsymbolic
При создании разделяемой библиотеки привязывать ссылки на глобальные символы
к определению внутри разделяемой библиотеки, если оно существует. Нормально,
программа, связанная с разделяемой библиотекой, может переопределить определение
внутри разделяемой библиотеки. Эта опция осмысленна только на платформах ELF,
поддерживающих разделяемые библиотеки.
-Bsymbolic-functions
При создании разделяемой библиотеки привязывать ссылки на глобальные символы
функций к определению внутри разделяемой библиотеки, если оно существует.
Эта опция осмысленна только на платформах ELF, поддерживающих разделяемые
библиотеки.
-Bno-symbolic
Эта опция может отменить предыдущие -Bsymbolic и -Bsymbolic-functions.
--dynamic-list=dynamic-list-file
Указать имя файла динамического списка связывателю. Это обычно используется
при создании разделяемых библиотек для указания списка глобальных символов,
ссылки на которые не должны привязываться к определению внутри разделяемой
библиотеки, или при создании динамически связываемых исполняемых файлов
для указания списка символов, которые должны быть добавлены в таблицу символов
в исполняемом файле. Эта опция осмысленна только на платформах ELF, поддерживающих
разделяемые библиотеки.
Формат динамического списка такой же, как узел версии без области видимости
и имени узла. См. VERSION для дополнительной информации.
--dynamic-list-data
Включить все глобальные символы данных в динамический список.
--dynamic-list-cpp-new
Предоставить встроенный динамический список для операторов C++ new и delete.
Это в основном полезно для построения разделяемой libstdc++.
--dynamic-list-cpp-typeinfo
Предоставить встроенный динамический список для идентификации типов во время
выполнения C++.
--check-sections
--no-check-sections
Просит связыватель не проверять адреса разделов после их назначения, чтобы
увидеть, есть ли пересечения. Нормально связыватель выполнит эту проверку, и если
найдёт пересечения, произведёт подходящие сообщения об ошибках. Связыватель знает
о разделах в наложениях и делает для них скидки. Поведение по умолчанию может быть
восстановлено с помощью опции командной строки --check-sections. Пересечение
разделов обычно не проверяется для связываний с возможностью перераспределения.
Вы можете принудить проверку в этом случае с помощью опции --check-sections.
--copy-dt-needed-entries
--no-copy-dt-needed-entries
Эта опция влияет на обработку динамических библиотек, на которые ссылаются
тегами DT_NEEDED внутри динамических библиотек ELF, упомянутых в командной строке.
Нормально связыватель не добавит тег DT_NEEDED в выходной бинарник для каждой
библиотеки, упомянутой в теге DT_NEEDED во входной динамической библиотеке.
С --copy-dt-needed-entries, указанной в командной строке, записи DT_NEEDED
любых динамических библиотек, следующих за ней, будут добавлены. Поведение по
умолчанию может быть восстановлено с --no-copy-dt-needed-entries.
Эта опция также влияет на разрешение символов в динамических библиотеках.
С --copy-dt-needed-entries динамические библиотеки, упомянутые в командной строке,
будут рекурсивно искаться, следуя их тегам DT_NEEDED к другим библиотекам, для
разрешения символов, требуемых выходным бинарником. С значением по умолчанию
однако поиск динамических библиотек, следующих за ней, остановится на самой
динамической библиотеке. Ссылки DT_NEEDED не будут проследованы для разрешения
символов.
--cref
Вывести таблицу перекрестных ссылок. Если генерируется файл карты связывания,
таблица перекрестных ссылок печатается в файл карты. В противном случае, она
печатается в стандартный вывод.
Формат таблицы намеренно прост, чтобы его можно было легко обработать скриптом,
если это необходимо. Символы выводятся, отсортированные по имени. Для каждого
символа приводится список имён файлов. Если символ определён, первый перечисленный
файл — это местоположение определения. Если символ определён как общее значение,
то любые файлы, где это происходит, появляются следующими. Наконец, любые файлы,
которые ссылаются на символ, перечислены.
--ctf-variables
--no-ctf-variables
Формат отладочной информации CTF поддерживает раздел, который кодирует имена
и типы переменных, найденных в программе, которые не появляются в таблице символов.
Эти переменные явно нельзя искать по адресу обычными отладчиками, так что место,
используемое для их типов и имён, обычно тратится впустую: типы обычно малы, но
имена часто нет. --ctf-variables вызывает генерацию такого раздела. Значение
по умолчанию может быть восстановлено с --no-ctf-variables.
--ctf-share-types=method
Настроить метод обмена типами между единицами перевода в CTF.
share-unconflicted
Поместить все типы, у которых нет неоднозначных определений, в общий словарь,
где отладчики могут легко к ним получить доступ, даже если они встречаются только
в одной единице перевода. Это значение по умолчанию.
share-duplicated
Поместить только типы, которые встречаются в нескольких единицах перевода,
в общий словарь: типы с одним определением переходят в словари на единицу перевода.
Типы с неоднозначными определениями в нескольких единицах перевода всегда переходят
в словари на единицу перевода. Это склоняет к увеличению CTF, но может уменьшить
количество CTF в общем словаре. Для очень больших проектов это может ускорить
открытие CTF и сэкономить память в потребителе CTF во время выполнения.
--no-define-common
Эта опция запрещает назначение адресов общим символам. Команда скрипта
"INHIBIT_COMMON_ALLOCATION" имеет тот же эффект.
Опция --no-define-common позволяет отделить решение о назначении адресов общим
символам от выбора типа выходного файла; в противном случае ненераспределяемый
выходной тип заставляет назначать адреса общим символам. Использование --no-define-common
позволяет общим символам, на которые ссылаются из разделяемой библиотеки, назначать
адреса только в основной программе. Это устраняет ненужное дублированное пространство
в разделяемой библиотеке и также предотвращает любую возможную путаницу при разрешении
неправильного дубликата, когда есть много динамических модулей со специализированными
путями поиска для разрешения символов во время выполнения.
--force-group-allocation
Эта опция заставляет связыватель размещать члены группы разделов как обычные
входные разделы и удалять группы разделов. Это поведение по умолчанию для
финального связывания, но эту опцию можно использовать для изменения поведения
связывания с возможностью перераспределения (-r). Команда скрипта "FORCE_GROUP_ALLOCATION"
имеет тот же эффект.
--defsym=symbol=expression
Создать глобальный символ в выходном файле, содержащий абсолютный адрес,
данный expression. Вы можете использовать эту опцию столько раз, сколько
необходимо, чтобы определить несколько символов в командной строке. Поддерживается
ограниченная форма арифметики для expression в этом контексте: вы можете
указать шестнадцатеричное постоянное значение или имя существующего символа,
или использовать "+" и "-" для добавления или вычитания шестнадцатеричных
постоянных значений или символов. Если вам нужны более сложные выражения,
рассмотрите использование языка команд связывателя из скрипта. Замечание: между
symbol, знаком равенства ("=") и expression не должно быть пробелов.
Связыватель обрабатывает аргументы --defsym и -T в порядке, размещение --defsym
перед -T определит символ перед обработкой скрипта связывателя от -T, в то время
как размещение --defsym после -T определит символ после обработки скрипта связывателя.
Это имеет последствия для выражений в скрипте связывателя, которые используют
символы --defsym, какой порядок правильный, будет зависеть от того, чего вы
пытаетесь достичь.
--demangle[=style]
--no-demangle
Эти опции управляют разманглированием имён символов в сообщениях об ошибках
и другом выводе. Когда связыватель указан на разманглирование, он пытается
представить имена символов в читаемом виде: он удаляет ведущие подчёркивания,
если они используются форматом объектного файла, и преобразует заманглированные
имена символов C++ в читаемые имена пользователя. Разные компиляторы имеют
разные стили манглинга. Необязательный аргумент стиля разманглирования может
использоваться для выбора подходящего стиля разманглирования для вашего компилятора.
Связыватель будет разманглировать по умолчанию, если переменная окружения
COLLECT_NO_DEMANGLE не установлена. Эти опции могут использоваться для переопределения.
-Ifile
--dynamic-linker=file
Установить имя динамического связывателя. Это осмысленно только при генерации
динамически связываемых исполняемых файлов ELF. Динамический связыватель по умолчанию
обычно правильный; не используйте это, если вы не знаете, что делаете.
--no-dynamic-linker
При создании исполняемого файла пропустить запрос динамического связывателя
для использования во время загрузки. Это осмысленно только для исполняемых файлов
ELF, которые содержат динамические релокации, и обычно требует кода точки входа,
способного обрабатывать эти релокации.
--embedded-relocs
Эта опция похожа на опцию --emit-relocs, за исключением того, что релокации
хранятся в разделе, специфичном для цели. Эта опция поддерживается только
для целей BFIN, CR16 и M68K.
--disable-multiple-abs-defs
Не разрешать несколько определений с символами, включёнными в filename, вызванный -R
или --just-symbols.
--fatal-warnings
--no-fatal-warnings
Считать все предупреждения ошибками. Поведение по умолчанию может быть восстановлено
с опцией --no-fatal-warnings.
-w
--no-warnings
Не отображать никаких сообщений о предупреждениях или ошибках. Это переопределяет
--fatal-warnings, если она включена. Эта опция может использоваться, когда известно,
что выходной бинарник не будет работать, но всё равно нужно создать его.
--force-exe-suffix
Убедиться, что выходной файл имеет суффикс .exe.
Если успешно построенный полностью связанный выходной файл не имеет суффикса
".exe" или ".dll", эта опция заставит связыватель скопировать выходной файл
в файл с тем же именем с суффиксом ".exe". Эта опция полезна при использовании
немодифицированных makefile Unix на хосте Microsoft Windows, поскольку некоторые
версии Windows не запустят образ, если он не заканчивается на ".exe".
--gc-sections
--no-gc-sections
Включить сбор мусора неиспользуемых входных разделов. Это игнорируется на целях,
которые не поддерживают эту опцию. Поведение по умолчанию (не выполнять этот сбор
мусора) может быть восстановлено путём указания --no-gc-sections в командной строке.
Замечание, что сбор мусора для форматов COFF и PE поддерживается, но реализация
в настоящее время считается экспериментальной.
--gc-sections определяет, какие входные разделы используются, путем осмотра символов
и релокаций. Раздел, содержащий символ входа, и все разделы, содержащие символы,
неопределённые в командной строке, будут сохранены, а также разделы, содержащие
символы, на которые ссылаются динамические объекты. Замечание, что при построении
разделяемых библиотек связыватель должен предположить, что любой видимый символ
ссылается. Как только этот начальный набор разделов определён, связыватель рекурсивно
помечает как используемые любой раздел, на который ссылаются их релокации. См. --entry,
--undefined и --gc-keep-exported.
Эта опция может быть установлена при частичном связывании (включено опцией -r).
В этом случае корень сохранённых символов должен быть явно указан либо одной из
опций --entry, --undefined или --gc-keep-exported, либо командой "ENTRY" в скрипте
связывателя.
Как расширение GNU, входные разделы ELF, помеченные флагом "SHF_GNU_RETAIN", не будут
собраны мусором.
--print-gc-sections
--no-print-gc-sections
Перечислить все разделы, удалённые сборщиком мусора. Список печатается в stderr.
Эта опция эффективна только если сбор мусора включён опцией --gc-sections. Поведение
по умолчанию (не перечислять разделы, которые удалены) может быть восстановлено
путём указания --no-print-gc-sections в командной строке.
--gc-keep-exported
Когда --gc-sections включено, эта опция предотвращает сбор мусора неиспользуемых
входных разделов, которые содержат глобальные символы с видимостью default или protected.
Эта опция предназначена для использования в исполняемых файлах, где неиспользуемые
разделы в противном случае были бы собраны мусором независимо от внешней видимости
содержащихся символов. Замечание, что эта опция не имеет эффекта при связывании
разделяемых объектов, поскольку это уже поведение по умолчанию. Эта опция поддерживается
только для целевых платформ ELF.
--print-output-format
Печатать имя формата вывода по умолчанию (возможно, повлиянное другими опциями
командной строки). Это строка, которая появится в команде скрипта связывателя
"OUTPUT_FORMAT".
--print-memory-usage
Печатать использованный размер, общий размер и использованный размер регионов
памяти, созданных командой MEMORY. Это полезно для встроенных целей, чтобы иметь
быстрый обзор количества свободной памяти. Формат вывода имеет один заголовок
и одну строку на регион. Он удобен для чтения человеком и легко анализируется
инструментами. Вот пример вывода:
Memory region Used Size Region Size %age Used
ROM: 256 KB 1 MB 25.00%
RAM: 32 B 2 GB 0.00%
--help
Печатать сводку опций командной строки в стандартный вывод и выйти.
--target-help
Печатать сводку всех целевых опций в стандартный вывод и выйти.
-Map=mapfile
Печатать карту связывания в файл mapfile. См. описание опции -M выше. Если mapfile
— просто символ "-", то карта будет записана в stdout.
Указание каталога как mapfile заставляет связыватель записать карту связывания
как файл внутри каталога. Нормально имя файла внутри каталога вычисляется как
базовое имя выходного файла с добавлением ".map". Однако, если используется
специальный символ "%", то это будет заменено полным путём выходного файла.
Кроме того, если после символа % есть какие-либо символы, то ".map" больше не
будет добавлено.
-o foo.exe -Map=bar [Создаёт ./bar]
-o ../dir/foo.exe -Map=bar [Создаёт ./bar]
-o foo.exe -Map=../dir [Создаёт ../dir/foo.exe.map]
-o ../dir2/foo.exe -Map=../dir [Создаёт ../dir/foo.exe.map]
-o foo.exe -Map=% [Создаёт ./foo.exe.map]
-o ../dir/foo.exe -Map=% [Создаёт ../dir/foo.exe.map]
-o foo.exe -Map=%.bar [Создаёт ./foo.exe.bar]
-o ../dir/foo.exe -Map=%.bar [Создаёт ../dir/foo.exe.bar]
-o ../dir2/foo.exe -Map=../dir/% [Создаёт ../dir/../dir2/foo.exe.map]
-o ../dir2/foo.exe -Map=../dir/%.bar [Создаёт ../dir/../dir2/foo.exe.bar]
Это ошибка указать более одного символа "%".
Если файл карты уже существует, он будет перезаписан этой операцией.
--no-keep-memory
ld обычно оптимизирует скорость за счёт использования памяти путём кэширования
таблиц символов входных файлов в памяти. Эта опция говорит ld оптимизировать
использование памяти, перечитывая таблицы символов по необходимости. Это может
потребоваться, если ld выходит из памяти во время связывания большого исполняемого
файла.
--no-undefined
-z defs
Сообщать о неразрешённых ссылках на символы из обычных объектных файлов. Это
делается даже если связыватель создаёт несимволическую разделяемую библиотеку.
Переключатель --[no-]allow-shlib-undefined контролирует поведение для сообщений
о неразрешённых ссылках, найденных в разделяемых библиотеках, которые связываются.
Эффекты этой опции могут быть отменены с помощью "-z undefs".
--allow-multiple-definition
-z muldefs
Нормально, если символ определён несколько раз, связыватель сообщит о фатальной
ошибке. Эти опции позволяют несколько определений, и будет использовано первое
определение.
--allow-shlib-undefined
--no-allow-shlib-undefined
Разрешает или запрещает неопределённые символы в разделяемых библиотеках. Этот
переключатель похож на --no-undefined, за исключением того, что он определяет
поведение, когда неопределённые символы находятся в разделяемой библиотеке, а не
в обычном объектном файле. Это не влияет на обработку неопределённых символов
в обычных объектных файлах.
Поведение по умолчанию — сообщать об ошибках для любых неопределённых символов,
на которые ссылаются в разделяемых библиотеках, если связыватель используется
для создания исполняемого файла, но разрешать их, если связыватель используется
для создания разделяемой библиотеки.
Причины разрешения неопределённых ссылок на символы в разделяемых библиотеках,
указанных во время связывания, следующие:
• Разделяемая библиотека, указанная во время связывания, может отличаться от
той, которая доступна во время загрузки, так что символ может быть разрешён
во время загрузки.
• Существуют некоторые операционные системы, например BeOS и HPPA, где неопределённые
символы в разделяемых библиотеках нормальны.
Например, ядро BeOS патчит разделяемые библиотеки во время загрузки для выбора
наиболее подходящей функции для текущей архитектуры. Это используется, например,
для динамического выбора подходящей функции memset.
--error-handling-script=scriptname
Если эта опция предоставлена, связыватель вызовет scriptname при возникновении
ошибки. В настоящее время однако поддерживаются только два вида ошибок: отсутствующие
символы и отсутствующие библиотеки. Два аргумента будут переданы скрипту: ключевое
слово "undefined-symbol" или `missing-lib" и имя неопределённого символа или
отсутствующей библиотеки. Намерение заключается в том, что скрипт предоставит
предложения пользователю, где символ или библиотека могут быть найдены. После
завершения скрипта нормальное сообщение об ошибке связывателя будет отображено.
Доступность этой опции управляется переключателем во время настройки, так что
она может отсутствовать в конкретных реализациях.
--no-undefined-version
Нормально, если символ имеет неопределённую версию, связыватель игнорирует его.
Эта опция запрещает символы с неопределённой версией, и вместо этого будет выдана
фатальная ошибка.
--default-symver
Создать и использовать версию символа по умолчанию (soname) для неверсионированных
экспортируемых символов.
--default-imported-symver
Создать и использовать версию символа по умолчанию (soname) для неверсионированных
импортируемых символов.
--no-warn-mismatch
Нормально ld выдаст ошибку, если вы попытаетесь связать входные файлы, которые
несовместимы по какой-то причине, возможно, потому что они были скомпилированы
для разных процессоров или для разных порядков эндианов. Эта опция говорит ld,
что он должен тихо разрешить такие возможные ошибки. Используйте эту опцию
с осторожностью, в случаях, когда вы предприняли специальные действия, чтобы
убедиться, что ошибки связывателя неуместны.
--no-warn-search-mismatch
Нормально ld выдаст предупреждение, если найдёт несовместимую библиотеку во время
поиска библиотеки. Эта опция подавляет предупреждение.
--no-whole-archive
Отключить эффект опции --whole-archive для последующих архивных файлов.
--noinhibit-exec
Сохранить исполняемый выходной файл, когда он всё ещё usable. Нормально связыватель
не произведёт выходной файл, если столкнётся с ошибками во время процесса связывания;
он выходит без записи выходного файла, когда выдаёт любую ошибку.
-nostdlib
Искать каталоги библиотек только явно указанные в командной строке. Каталоги
библиотек, указанные в скриптах связывателя (включая скрипты связывателя,
указанные в командной строке), игнорируются.
--oformat=output-format
ld может быть настроен для поддержки нескольких видов объектных файлов. Если
ваш ld настроен таким образом, вы можете использовать опцию --oformat для указания
двоичного формата для выходного объектного файла. Даже если ld настроен для
поддержки альтернативных форматов объектных файлов, вам обычно не нужно это
указывать, поскольку ld должен быть настроен для производства форматом вывода
по умолчанию наиболее обычного формата на каждой машине. output-format — строка
текста, название конкретного формата, поддерживаемого библиотеками BFD. (Вы можете
перечислить доступные двоичные форматы с objdump -i.) Команда скрипта "OUTPUT_FORMAT"
также может указать формат вывода.
--out-implib file
Создать импортную библиотеку в file, соответствующую исполняемому файлу, который
создаёт связыватель (например, DLL или программа ELF). Эта импортная библиотека
(которая должна называться "*.dll.a" или "*.a" для DLL) может использоваться
для связывания клиентов с созданным исполняемым файлом; это поведение позволяет
пропустить отдельный шаг создания импортной библиотеки (например, "dlltool" для DLL).
Эта опция доступна только для целевых платформ i386 PE и ELF связывателя.
-pie
--pic-executable
Создать позиционно-независимый исполняемый файл. Это в настоящее время поддерживается
только на платформах ELF. Позиционно-независимые исполняемые файлы перераспределяются
динамическим связывателем на виртуальный адрес, который OS выбирает для них, и это
может варьироваться между вызовами. Они помечаются как ET_DYN в заголовке ELF-файла,
но отличаются от разделяемых библиотек по ряду способов. В частности, определённые
символы в PIE по умолчанию не могут быть переопределены другим объектом, как они
могут в разделяемой библиотеке.
-no-pie
Создать позиционно-зависимый исполняемый файл. Это значение по умолчанию.
-qmagic
Эта опция игнорируется для совместимости с Linux.
-Qy Эта опция игнорируется для совместимости с SVR4.
--relax
--no-relax
Опция с эффектами, зависящими от машины. Эта опция поддерживается только на
нескольких целях.
На некоторых платформах опция --relax выполняет целевые глобальные оптимизации,
которые становятся возможными, когда связыватель разрешает адреса в программе,
такие как релаксация режимов адресации, синтез новых инструкций, выбор более
коротких версий текущих инструкций и объединение постоянных значений.
На некоторых платформах эти глобальные оптимизации во время связывания могут
сделать символьную отладку результирующего исполняемого файла невозможной. Это
известно для семейства процессоров Matsushita MN10200 и MN10300.
На платформах, где функция поддерживается, опция --no-relax отключит её.
На платформах, где функция не поддерживается, как --relax, так и --no-relax
принимаются, но игнорируются.
--retain-symbols-file=filename
Сохранить только символы, перечисленные в файле filename, отбросив все остальные.
filename — это просто плоский файл, с одним именем символа на строку. Эта опция
особенно полезна в средах (таких как VxWorks), где постепенно накапливается
большая глобальная таблица символов, чтобы сэкономить память во время выполнения.
--retain-symbols-file не отбрасывает неопределённые символы или символы,
нужные для релокаций.
Вы можете указать --retain-symbols-file только один раз в командной строке.
Она переопределяет -s и -S.
-rpath=dir
Добавить каталог в путь поиска библиотек во время выполнения. Это используется
при связывании исполняемого файла ELF с разделяемыми объектами. Все аргументы -rpath
объединяются и передаются рантайм-связывателю, который использует их для поиска
разделяемых объектов во время выполнения.
Опция -rpath также используется при поиске разделяемых объектов, которые нужны
разделяемым объектам, явно включённым в связывание; см. описание опции -rpath-link.
Поиск -rpath таким образом поддерживается только нативными связывателями и
кросс-связывателями, настроенными с опцией --with-sysroot.
Если -rpath не используется при связывании исполняемого файла ELF, содержимое
переменной окружения "LD_RUN_PATH" будет использовано, если оно определено.
Опция -rpath также может использоваться на SunOS. По умолчанию на SunOS связыватель
сформирует путь поиска во время выполнения из всех опций -L, которые ему даны.
Если используется опция -rpath, путь поиска во время выполнения будет сформирован
исключительно из опций -rpath, игнорируя опции -L. Это может быть полезно при
использовании gcc, который добавляет много опций -L, которые могут быть на
файловых системах, монтируемых по NFS.
Для совместимости с другими связывателями ELF, если опция -R следует за именем
каталога, а не именем файла, она обрабатывается как опция -rpath.
-rpath-link=dir
При использовании ELF или SunOS одна разделяемая библиотека может требовать другую.
Это происходит, когда связывание "ld -shared" включает разделяемую библиотеку
как один из входных файлов.
Когда связыватель сталкивается с такой зависимостью при выполнении неспециального,
неспециализированного связывания, он автоматически попытается найти требуемую
разделяемую библиотеку и включить её в связывание, если она не включена явно.
В таком случае несколько каталогов ищутся, как описано ниже. Опция -rpath-link
указывает первый набор каталогов для поиска. Эта опция может указывать последовательность
имён каталогов либо путём предоставления списка имён, разделённых двоеточиями,
либо путём появления несколько раз.
Токены $ORIGIN и $LIB могут появляться в этих каталогах поиска. Они будут
заменены полным путём к каталогу, содержащему программу или разделяемый объект
в случае $ORIGIN и либо lib — для 32-битных бинарников — либо lib64 — для 64-битных
бинарников — в случае $LIB.
Альтернативная форма этих токенов — ${ORIGIN} и ${LIB} также может использоваться.
Токен $PLATFORM не поддерживается.
Опцию --rpath-link следует использовать с осторожностью, поскольку она переопределяет
путь поиска, который может быть закреплён в разделяемой библиотеке. В таком случае
возможно непреднамеренное использование другого пути поиска, чем тот, который
использовал бы рантайм-связыватель.
Когда требуются дополнительные разделяемые библиотеки, связыватель будет искать
каталоги в порядке, перечисленном ниже, чтобы найти их. Замечание однако, что
это применяется только к дополнительным библиотекам, нужным для удовлетворения
уже включённых разделяемых библиотек. Это не применяется к библиотекам, которые
включены через опцию -l командной строки. Поиски библиотек -l проводятся только
в каталогах, указанных опцией -L.
1. Любые каталоги, указанные опциями -rpath-link.
2. Любые каталоги, указанные опциями -rpath. Разница между -rpath и -rpath-link
в том, что каталоги, указанные опциями -rpath, включаются в исполняемый файл
и используются во время выполнения, в то время как опция -rpath-link эффективна
только во время связывания. Поиск -rpath таким образом поддерживается только
нативными связывателями и кросс-связывателями, настроенными с опцией --with-sysroot.
3. На системе ELF для нативных связывателей, если опции -rpath и -rpath-link
не использовались, искать содержимое переменной окружения "LD_RUN_PATH".
4. На SunOS, если опция -rpath не использовалась, искать любые каталоги,
указанные опциями -L.
5. Для нативного связывателя искать содержимое переменной окружения "LD_LIBRARY_PATH".
6. Для нативного связывателя ELF каталоги в "DT_RUNPATH" или "DT_RPATH" разделяемой
библиотеки ищутся для разделяемых библиотек, нужных ей. Записи "DT_RPATH" игнорируются,
если существуют записи "DT_RUNPATH".
7. Для связывателя для системы Linux, если файл /etc/ld.so.conf существует,
список каталогов, найденных в этом файле. Замечание: путь к этому файлу
предшествует значению "sysroot", если оно определено, и затем любой строке
"prefix", если связыватель был настроен с опцией --prefix=<path>.
8. Для нативного связывателя на системе FreeBSD любые каталоги, указанные
макросом "_PATH_ELF_HINTS", определённым в файле заголовка elf-hints.h.
9. Любые каталоги, указанные командой "SEARCH_DIR" в скрипте связывателя,
указанном в командной строке, включая скрипты, указанные -T (но не -dT).
10. Каталоги по умолчанию, нормально /lib и /usr/lib.
11. Любые каталоги, указанные плагином LDPT_SET_EXTRA_LIBRARY_PATH.
12. Любые каталоги, указанные командой "SEARCH_DIR" в скрипте связывателя по умолчанию.
Замечание однако на системах на основе Linux есть дополнительная оговорка: Если
опция --as-needed активна и найдена разделяемая библиотека, которая обычно удовлетворит
поиск, и эта библиотека не имеет тега DT_NEEDED для libc.so, и есть разделяемая
библиотека позже в наборе каталогов поиска, которая также удовлетворяет поиск,
и эта вторая разделяемая библиотека имеет тег DT_NEEDED для libc.so, то вторая
библиотека будет выбрана вместо первой.
Если требуемая разделяемая библиотека не найдена, связыватель выдаст предупреждение
и продолжит связывание.
--section-ordering-file=script
Эта опция используется для дополнения текущего скрипта связывателя дополнительным
отображением входных разделов на выходные разделы. Этот файл должен использовать
тот же синтаксис для "SECTIONS", что и в нормальных скриптах связывателя, но
он должен делать только отображение входных разделов на выходные разделы. @pxref{SECTIONS}
Второе ограничение на скрипт упорядочения разделов заключается в том, что он
может ссылаться только на выходные разделы, которые уже определены тем скриптом
связывателя, который в настоящее время используется. (Т.е. скриптом связывателя
по умолчанию или скриптом, указанным в командной строке). Преимущество скрипта
упорядочения разделов заключается в том, что входные разделы отображаются на
начало выходных разделов, так что они могут обеспечить упорядочение разделов
в выходном разделе. Например, представьте, что скрипт связывателя по умолчанию
выглядит так:
SECTIONS {
.text : { *(.text.hot) ; *(.text .text.*) }
.data : { *(.data.big) ; *(.data .data.*) }
}
Тогда, если используется скрипт упорядочения разделов вроде этого:
.text : { *(.text.first) ; *(.text.z*) }
.data : { foo.o(.data.first) ; *(.data.small) }
Это будет эквивалентно скрипту связывателя вроде этого:
SECTIONS {
.text : { *(.text.first) ; *(.text.z*) ; *(.text.hot) ; *(.text .text.*) }
.data : { foo.o(.data.first) ; *(.data.small) ; *(.data.big) ; *(.data .data.*) }
}
Преимущество скрипта упорядочения разделов заключается в том, что он может
использоваться для упорядочения тех разделов, которые важны для пользователя,
без необходимости беспокоиться о других разделах, регионах памяти или чём-либо
ещё.
-shared
-Bshareable
Создать разделяемую библиотеку. Это в настоящее время поддерживается только
на платформах ELF, XCOFF и SunOS. На SunOS связыватель автоматически создаст
разделяемую библиотеку, если опция -e не используется и в связывании есть
неопределённые символы.
--sort-common
--sort-common=ascending
--sort-common=descending
Эта опция говорит ld сортировать общие символы по выравниванию в восходящем
или нисходящем порядке при размещении их в соответствующих выходных разделах.
Рассматриваемые выравнивания символов — шестнадцатеричное или больше, восьмеричное,
четвертичное, двухбайтовое и однобайтовое. Это для предотвращения разрывов между
символами из-за ограничений выравнивания. Если порядок сортировки не указан,
предполагается нисходящий порядок.
--sort-section=name
Эта опция применит "SORT_BY_NAME" ко всем шаблонам разделов с подстановочными
знаками в скрипте связывателя.
--sort-section=alignment
Эта опция применит "SORT_BY_ALIGNMENT" ко всем шаблонам разделов с подстановочными
знаками в скрипте связывателя.
--spare-dynamic-tags=count
Эта опция указывает количество пустых слотов, которые следует оставить в разделе
.dynamic разделяемых объектов ELF. Пустые слоты могут потребоваться инструментами
постобработки, такими как prelinker. Значение по умолчанию — 5.
--split-by-file[=size]
Похоже на --split-by-reloc, но создаёт новый выходной раздел для каждого входного
файла, когда достигается size. size по умолчанию равно 1, если не указано.
--split-by-reloc[=count]
Пытаться создавать дополнительные разделы в выходном файле, так чтобы ни один
выходной раздел в файле не содержал более count релокаций. Это полезно при генерации
огромных файлов с возможностью перераспределения для загрузки в определённые
ядра реального времени с форматом объектного файла COFF; поскольку COFF не может
представлять более 65535 релокаций в одном разделе. Замечание, что это не сработает
с форматами объектных файлов, которые не поддерживают произвольные разделы. Связыватель
не разобьёт индивидуальные входные разделы для перераспределения, так что если
один входной раздел содержит более count релокаций, один выходной раздел будет
содержать столько релокаций. count по умолчанию равно 32768.
--stats
Вычислить и отобразить статистику о работе связывателя, такую как время выполнения
и использование памяти.
--sysroot=directory
Использовать directory как местоположение sysroot, переопределяя значение по
умолчанию во время настройки. Эта опция поддерживается только связывателями,
настроенными с --with-sysroot.
--task-link
Это используется для целей на основе COFF/PE для создания объектного файла,
связанного с задачей, где все глобальные символы были преобразованы в статические.
--traditional-format
Для некоторых целей вывод ld отличается по некоторым аспектам от вывода некоторых
существующих связывателей. Этот переключатель запрашивает ld использовать традиционный
формат вместо этого.
Например, на SunOS ld объединяет дублирующиеся записи в строковой таблице символов.
Это может уменьшить размер выходного файла с полной отладочной информацией более
чем на 30 процентов. К сожалению, программа dbx SunOS не может читать результирующую
программу (gdb не имеет проблем). Опция --traditional-format говорит ld не объединять
дублирующиеся записи.
--section-start=sectionname=org
Разместить раздел в выходном файле по абсолютному адресу, указанному org.
Вы можете использовать эту опцию столько раз, сколько необходимо, для размещения
нескольких разделов в командной строке. org должно быть одним шестнадцатеричным
целым числом; для совместимости с другими связывателями вы можете опустить ведущий
0x, обычно ассоциируемый с шестнадцатеричными значениями. Замечание: между sectionname,
знаком равенства ("=") и org не должно быть пробелов.
--image-base=org
При использовании ELF то же, что и -Ttext-segment, с обеими опциями, эффективно
устанавливающими базовый адрес исполняемого файла ELF.
При использовании PE использовать value как базовый адрес вашей программы или dll.
Это самый низкий адрес памяти, который будет использоваться, когда ваша программа
или dll загружается. Чтобы уменьшить необходимость в перераспределении и улучшить
производительность dll, каждая должна иметь уникальный базовый адрес и не пересекаться
с другими dll. Значение по умолчанию — 0x400000 для исполняемых файлов и 0x10000000
для dll.
-Tbss=org
-Tdata=org
-Ttext=org
То же, что и --section-start, с ".bss", ".data" или ".text" как sectionname.
-Ttext-segment=org
При создании исполняемого файла ELF установить адрес первого байта первого
сегмента. Замечание, что когда -pie используется с -Ttext-segment=org, выходной
исполняемый файл помечается как ET_EXEC, так что адрес первого байта сегмента
текста будет гарантированно равен org во время выполнения.
-Trodata-segment=org
При создании исполняемого файла ELF или разделяемого объекта для цели, где
данные только для чтения находятся в собственном сегменте, отдельном от исполняемого
текста, установить адрес первого байта сегмента данных только для чтения.
-Tldata-segment=org
При создании исполняемого файла ELF или разделяемого объекта для модели памяти
x86-64 medium установить адрес первого байта сегмента ldata.
--unresolved-symbols=method
Определить, как обрабатывать неразрешённые символы. Возможные значения для method:
ignore-all
Не сообщать о каких-либо неразрешённых символах.
report-all
Сообщать обо всех неразрешённых символах. Это значение по умолчанию.
ignore-in-object-files
Сообщать о неразрешённых символах, которые содержатся в разделяемых библиотеках,
но игнорировать их, если они приходят из обычных объектных файлов.
ignore-in-shared-libs
Сообщать о неразрешённых символах, которые приходят из обычных объектных файлов,
но игнорировать их, если они приходят из разделяемых библиотек. Это может быть
полезно при создании динамического бинарника и известно, что все разделяемые
библиотеки, на которые он должен ссылаться, включены в командную строку связывателя.
Поведение для разделяемых библиотек само по себе также может контролироваться
опцией --[no-]allow-shlib-undefined.
Нормально связыватель сгенерирует сообщение об ошибке для каждого сообщённого
неразрешённого символа, но опция --warn-unresolved-symbols может изменить это
на предупреждение.
--dll-verbose
--verbose[=NUMBER]
Показать номер версии ld и перечислить поддерживаемые эмуляции связывателя.
Показать, какие входные файлы можно и нельзя открыть. Показать скрипт связывателя,
используемый связывателем. Если необязательный аргумент NUMBER > 1, статус символов
плагина также будет отображён.
--version-script=version-scriptfile
Указать имя скрипта версии связывателю. Это обычно используется при создании
разделяемых библиотек для указания дополнительной информации об иерархии версий
для библиотеки, которая создаётся. Эта опция полностью поддерживается только
на платформах ELF, поддерживающих разделяемые библиотеки; см. VERSION. Она частично
поддерживается на платформах PE, которые могут использовать скрипты версий для
фильтрации видимости символов в режиме автоэкспорта: любые символы, помеченные
как локальные в скрипте версии, не будут экспортироваться.
--warn-common
Предупреждать, когда общий символ объединяется с другим общим символом или
с определением символа. Связыватели Unix позволяют этой несколько небрежной
практике, но связыватели на некоторых других операционных системах нет. Эта
опция позволяет найти потенциальные проблемы от объединения глобальных символов.
К сожалению, некоторые библиотеки C используют эту практику, так что вы можете
получить некоторые предупреждения о символах в библиотеках, а также в ваших
программах.
Существуют три вида глобальных символов, иллюстрируемых здесь примерами C:
int i = 1;
Определение, которое помещается в инициализированный раздел данных выходного файла.
extern int i;
Неопределённая ссылка, которая не выделяет пространство. Должно быть либо
определение, либо общий символ для переменной где-то.
int i;
Общий символ. Если есть только (один или несколько) общих символов для переменной,
она помещается в неинициализированный раздел данных выходного файла. Связыватель
объединяет несколько общих символов для той же переменной в один символ. Если они
имеют разные размеры, он выбирает наибольший размер. Связыватель превращает общий
символ в объявление, если есть определение той же переменной.
Опция --warn-common может производить пять видов предупреждений. Каждое предупреждение
состоит из пары строк: первая описывает символ, только что встреченный, а вторая
описывает предыдущий символ, встреченный с тем же именем. Один или оба из двух
символов будут общими символами.
1. Преобразование общего символа в ссылку, потому что уже есть определение для символа.
<file>(<section>): warning: common of `<symbol>'
overridden by definition
<file>(<section>): warning: defined here
2. Преобразование общего символа в ссылку, потому что позже встречается определение
для символа. Это то же самое, что и предыдущий случай, за исключением того,
что символы встречаются в другом порядке.
<file>(<section>): warning: definition of `<symbol>'
overriding common
<file>(<section>): warning: common is here
3. Объединение общего символа с предыдущим общим символом одинакового размера.
<file>(<section>): warning: multiple common
of `<symbol>'
<file>(<section>): warning: previous common is here
4. Объединение общего символа с предыдущим большим общим символом.
<file>(<section>): warning: common of `<symbol>'
overridden by larger common
<file>(<section>): warning: larger common is here
5. Объединение общего символа с предыдущим меньшим общим символом. Это то же самое,
что и предыдущий случай, за исключением того, что символы встречаются в другом
порядке.
<file>(<section>): warning: common of `<symbol>'
overriding smaller common
<file>(<section>): warning: smaller common is here
--warn-constructors
Предупреждать, если используются какие-либо глобальные конструкторы. Это полезно
только для нескольких форматов объектных файлов. Для форматов вроде COFF или ELF
связыватель не может обнаружить использование глобальных конструкторов.
--warn-execstack
--warn-execstack-objects
--no-warn-execstack
На платформах ELF связыватель может генерировать сообщения о предупреждениях,
если ему поручено создать выходной файл, содержащий исполняемый стек. Существуют
три возможных состояния:
1. Не генерировать никаких предупреждений.
2. Всегда генерировать предупреждения, даже если исполняемый стек запрошен
опцией -z execstack командной строки.
3. Генерировать предупреждение только если объектный файл запрашивает исполняемый
стек, но не если используется опция -z execstack.
Значение по умолчанию зависит от того, как был настроен связыватель. Опция --no-warn-execstack
всегда ставит связыватель в состояние без предупреждений. Опция --warn-execstack ставит
связыватель в состояние warn-always. Опция --warn-execstack-objects ставит связыватель
в состояние warn-for-object-files-only.
Замечание: Входные файлы формата ELF могут указывать, что им нужен исполняемый
стек, имея раздел .note.GNU-stack с установленным битом исполняемости в флагах
раздела. Они могут указывать, что им не нужен исполняемый стек, имея тот же раздел,
но без установленного бита исполняемости. Если входной файл не имеет раздела
.note.GNU-stack, поведение по умолчанию специфично для цели. Для некоторых целей
отсутствие такого раздела подразумевает, что требуется исполняемый стек. Это часто
проблема для вручную созданных файлов ассемблера.
--error-execstack
--no-error-execstack
Если связыватель собирается генерировать сообщение о предупреждении об исполняемом,
записываемом сегменте или об исполняемом сегменте TLS, опция --error-execstack
превратит это предупреждение в ошибку. Опция --no-error-execstack восстановит
поведение по умолчанию, генерируя только сообщение о предупреждении.
Замечание — опция --error-execstack сама по себе не включает предупреждения
об этих сегментах. Эти предупреждения либо включены по умолчанию, если связыватель
настроен так, либо через опцию --warn-rwx-segments командной строки.
--warn-multiple-gp
Предупреждать, если требуются несколько значений глобального указателя в выходном
файле. Это осмысленно только для определённых процессоров, таких как Alpha.
Конкретно, некоторые процессоры помещают большие постоянные значения в специальный
раздел. Специальный регистр (глобальный указатель) указывает в середину этого раздела,
так что константы могут загружаться эффективно через режим адресации, относительно
базового регистра. Поскольку смещение в режиме относительно базового регистра фиксировано
и относительно мало (например, 16 бит), это ограничивает максимальный размер пула
констант. Таким образом, в больших программах часто необходимо использовать несколько
значений глобального указателя, чтобы обратиться ко всем возможным константам.
Эта опция вызывает предупреждение всякий раз, когда это случается.
--warn-once
Предупреждать только один раз для каждого неопределённого символа, а не один раз
на модуль, который на него ссылается.
--warn-rwx-segments
--no-warn-rwx-segments
Предупреждать, если связыватель создаёт загружаемый, ненулевой сегмент, у которого
установлены все три флага разрешений: чтение, запись и выполнение. Такой сегмент
представляет потенциальную уязвимость безопасности. Кроме того, будут генерироваться
предупреждения, если сегмент локального хранения потоков создаётся с флагом выполнения,
независимо от того, установлены ли флаги чтения и/или записи.
Эти предупреждения включены по умолчанию. Их можно отключить с помощью опции
--no-warn-rwx-segments и включить с помощью опции --warn-rwx-segments.
--error-rwx-segments
--no-error-rwx-segments
Если связыватель собирается генерировать сообщение о предупреждении об исполняемом,
записываемом сегменте, опция --error-rwx-segments превратит это предупреждение
в ошибку. Опция --no-error-rwx-segments восстановит поведение по умолчанию,
генерируя только сообщение о предупреждении.
Замечание — опция --error-rwx-segments сама по себе не включает предупреждения
об этих сегментах. Эти предупреждения либо включены по умолчанию, если связыватель
настроен так, либо через опцию --warn-rwx-segments командной строки.
--warn-section-align
Предупреждать, если адрес выходного раздела изменён из-за выравнивания. Обычно
выравнивание устанавливается входным разделом. Адрес изменится только если он
не указан явно; то есть, если команда "SECTIONS" не указывает начальный адрес
для раздела.
--warn-textrel
Предупреждать, если связыватель добавляет DT_TEXTREL в позиционно-независимый
исполняемый файл или разделяемый объект.
--warn-alternate-em
Предупреждать, если объект имеет альтернативный код машины ELF.
--warn-unresolved-symbols
Если связыватель собирается сообщить о неразрешённом символе (см. опцию
--unresolved-symbols), он обычно генерирует ошибку. Эта опция заставляет его
генерировать предупреждение вместо этого.
--error-unresolved-symbols
Это восстанавливает поведение связывателя по умолчанию, генерируя ошибки, когда
он сообщает о неразрешённых символах.
--whole-archive
Для каждого архива, упомянутого в командной строке после опции --whole-archive,
включить каждый объектный файл в архив в связывание, вместо поиска в архиве
требуемых объектных файлов. Это нормально используется для преобразования
архивного файла в разделяемую библиотеку, заставляя включить каждый объект.
Эта опция может быть использована несколько раз.
Два замечания при использовании этой опции с gcc: Во-первых, gcc не знает об
этой опции, так что вам нужно использовать -Wl,-whole-archive. Во-вторых, не
забудьте использовать -Wl,-no-whole-archive после вашего списка архивов, потому
что gcc добавит свой собственный список архивов в ваше связывание, и вы можете
не захотеть, чтобы этот флаг влиял на них тоже.
--wrap=symbol
Использовать функцию-обёртку для symbol. Любая неопределённая ссылка на symbol
будет разрешена как "__wrap_symbol". Любая неопределённая ссылка на "__real_symbol"
будет разрешена как symbol.
Это может использоваться для предоставления обёртки для системной функции.
Функция-обёртка должна называться "__wrap_symbol". Если она хочет вызвать
системную функцию, она должна вызвать "__real_symbol".
Вот тривиальный пример:
void *
__wrap_malloc (size_t c)
{
printf ("malloc called with %zu\n", c);
return __real_malloc (c);
}
Если вы свяжите другой код с этим файлом с --wrap malloc, то все вызовы "malloc"
вызовут функцию "__wrap_malloc" вместо этого. Вызов "__real_malloc" в "__wrap_malloc"
вызовет реальную функцию "malloc".
Вы можете захотеть предоставить функцию "__real_malloc" тоже, так чтобы связи
без опции --wrap работали. Если вы это сделаете, не помещайте определение "__real_malloc"
в тот же файл, что и "__wrap_malloc"; если вы сделаете это, ассемблер может разрешить
вызов перед тем, как связыватель получит шанс обернуть его в "malloc".
Только неопределённые ссылки заменяются связывателем. Таким образом, внутренние
ссылки единицы перевода на symbol не разрешаются как "__wrap_symbol". В следующем
примере вызов "f" в "g" не разрешается как "__wrap_f".
int
f (void)
{
return 123;
}
int
g (void)
{
return f();
}
--eh-frame-hdr
--no-eh-frame-hdr
Запросить (--eh-frame-hdr) или подавить (--no-eh-frame-hdr) создание раздела
".eh_frame_hdr" и заголовка сегмента ELF "PT_GNU_EH_FRAME".
--no-ld-generated-unwind-info
Запросить создание информации о размотке ".eh_frame" для разделов кода,
генерируемых связывателем, таких как PLT. Эта опция включена по умолчанию, если
информация о размотке, генерируемая связывателем, поддерживается. Эта опция также
контролирует генерацию информации трассировки стека ".sframe" для разделов кода,
генерируемых связывателем, таких как PLT.
--enable-new-dtags
--disable-new-dtags
Этот связыватель может создавать новые динамические теги в ELF. Но старые
системы ELF могут не понимать их. Если вы укажете --enable-new-dtags, новые
динамические теги будут созданы по необходимости, и старые динамические теги
будут omitted. Если вы укажете --disable-new-dtags, новые динамические теги
не будут созданы. По умолчанию новые динамические теги не создаются. Замечание,
что эти опции доступны только для систем ELF.
--hash-size=number
Установить размер хэш-таблиц связывателя по умолчанию в простое число, близкое
к number. Увеличение этого значения может уменьшить время, затрачиваемое связывателем
на выполнение задач, за счёт увеличения требований к памяти связывателя. Аналогично,
уменьшение этого значения может уменьшить требования к памяти за счёт скорости.
--hash-style=style
Установить тип хэш-таблиц связывателя. style может быть "sysv" для классического
раздела ELF ".hash", "gnu" для нового стиля раздела GNU ".gnu.hash" или "both"
для обоих классического ELF ".hash" и нового стиля GNU ".gnu.hash" хэш-таблиц.
Значение по умолчанию зависит от того, как был настроен связыватель, но для
большинства систем на основе Linux это будет "both".
--compress-debug-sections=none
--compress-debug-sections=zlib
--compress-debug-sections=zlib-gnu
--compress-debug-sections=zlib-gabi
--compress-debug-sections=zstd
На платформах ELF эти опции управляют сжатием разделов отладки DWARF с использованием zlib.
--compress-debug-sections=none не сжимает разделы отладки DWARF. --compress-debug-sections=zlib-gnu
сжимает разделы отладки DWARF и переименовывает их, чтобы они начинались с .zdebug вместо .debug.
--compress-debug-sections=zlib-gabi также сжимает разделы отладки DWARF, но вместо переименования
устанавливает флаг SHF_COMPRESSED в заголовках разделов.
Опция --compress-debug-sections=zlib является псевдонимом для --compress-debug-sections=zlib-gabi.
--compress-debug-sections=zstd сжимает разделы отладки DWARF с использованием zstd.
Замечание, что эта опция переопределяет любое сжатие во входных разделах отладки,
так что если бинарник связывается с --compress-debug-sections=none, например,
то любые сжатые разделы отладки во входных файлах будут разжаты перед копированием
в выходной бинарник.
Поведение сжатия по умолчанию варьируется в зависимости от вовлечённой цели
и опций настройки, использованных для построения инструментария. Значение по
умолчанию может быть определено путём осмотра вывода опции связывателя --help.
--reduce-memory-overheads
Эта опция уменьшает требования к памяти во время выполнения ld, за счёт скорости
связывания. Это было введено для выбора старого алгоритма O(n^2) для генерации
файла карты связывания, вместо нового алгоритма O(n), который использует около
40% больше памяти для хранения символов.
Другой эффект переключателя — установить размер хэш-таблицы по умолчанию в 1021,
что снова экономит память за счёт увеличения времени выполнения связывателя.
Однако это не делается, если использовалась опция --hash-size.
Опцию --reduce-memory-overheads также можно использовать для включения других
торгов в будущих версиях связывателя.
--max-cache-size=size
ld обычно кэширует информацию о релокациях и таблицы символов входных файлов
в памяти без ограничения размера. Эта опция устанавливает максимальный размер
кэша в size.
--build-id
--build-id=style
Запросить создание раздела ELF ".note.gnu.build-id" или раздела COFF ".buildid".
Содержимое заметки — уникальные биты, идентифицирующие этот связанный файл.
style может быть "uuid" для использования 128 случайных бит; "sha1" для использования
160-битного хэша SHA1, "md5" для использования 128-битного хэша MD5 или "xx" для
использования 128-битного XXHASH на нормативных частях содержимого вывода; или
"0xhexstring" для использования выбранной битовой строки, указанной как чётное
количество шестнадцатеричных цифр (символы "-" и ":" между парами цифр игнорируются).
Если style опущено, используется "sha1".
Стили "md5", "sha1" и "xx" производят идентификатор, который всегда одинаков
в идентичном выходном файле, но почти наверняка уникален среди всех неидентичных
выходных файлов. Он не предназначен для сравнения как контрольная сумма содержимого
файла. Связанный файл может быть изменён позже другими инструментами, но битовая
строка build ID, идентифицирующая оригинальный связанный файл, не изменится.
Передача "none" для style отключает установку из любых предыдущих опций "--build-id"
в командной строке.
--package-metadata=JSON
Запросить создание раздела ELF ".note.package". Содержимое заметки в формате JSON,
как указано в спецификации метаданных пакета. Для дополнительной информации см.:
https://systemd.io/ELF_PACKAGE_METADATA/ Аргумент JSON поддерживает кодирование
percent и следующее кодирование %[string] (где string относится к Named Character
References в HTML): %[comma] для ,, %[lbrace] для {, %[quot] для ", %[rbrace] для }
и %[space] для символа пробела. Если аргумент JSON отсутствует/пуст, то это отключит
создание заметки метаданных, если она была включена предыдущим появлением опции
--package-metadata. Если связыватель был построен с libjansson, то строка JSON
будет проверена.
Связыватель i386 PE поддерживает опцию -shared, которая заставляет вывод быть
динамически связываемой библиотекой (DLL) вместо нормального исполняемого файла.
Вы должны называть вывод "*.dll", когда используете эту опцию. Кроме того,
связыватель полностью поддерживает стандартные файлы "*.def", которые могут быть
указаны в командной строке связывателя как объектный файл (на самом деле, он должен
предшествовать архивам, из которых он экспортирует символы, чтобы убедиться, что
они связываются, как обычный объектный файл).
Кроме опций, общих для всех целей, связыватель i386 PE поддерживает дополнительные
опции командной строки, специфичные для цели i386 PE. Опции, которые принимают
значения, могут быть разделены от своих значений либо пробелом, либо знаком равенства.
--add-stdcall-alias
Если указано, символы с суффиксом stdcall (@nn) будут экспортироваться как есть
и также без суффикса. [Эта опция специфична для целевой платформы i386 PE связывателя]
--base-file file
Использовать file как имя файла, в котором сохранить базовые адреса всех релокаций,
нужных для генерации DLL с dlltool. [Это опция, специфичная для i386 PE]
--dll
Создать DLL вместо обычного исполняемого файла. Вы также можете использовать -shared
или указать "LIBRARY" в данном файле ".def". [Эта опция специфична для целевой
платформы i386 PE связывателя]
--enable-long-section-names
--disable-long-section-names
Варианты PE формата объектного файла COFF добавляют расширение, которое позволяет
использовать имена разделов длиннее восьми символов, нормальный лимит для COFF.
По умолчанию эти имена разрешены только в объектных файлах, поскольку полностью
связанные образы исполняемых файлов не несут строковую таблицу COFF, необходимую
для поддержки более длинных имён. Как расширение GNU, возможно разрешить их
использование и в образах исполняемых файлов, или (вероятно, бессмысленно!)
запретить в объектных файлах, используя эти две опции. Образы исполняемых файлов,
генерируемые с этими длинными именами разделов, слегка нестандартны, поскольку
они несут строковую таблицу, и могут генерировать путаный вывод при осмотре
с не-GNU инструментами, осведомлёнными о PE, такими как просмотрщики файлов и дамперы.
Однако, GDB полагается на использование длинных имён разделов PE для поиска разделов
информации отладки Dwarf-2 в образе исполняемого файла во время выполнения, и так
если ни одна опция не указана в командной строке, ld включит длинные имена разделов,
переопределяя поведение по умолчанию и технически правильное, когда найдёт наличие
информации отладки во время связывания образа исполняемого файла и не удаляя символы.
[Эта опция действительна для всех целевых платформ PE связывателя]
--enable-stdcall-fixup
--disable-stdcall-fixup
Если связыватель находит символ, который он не может разрешить, он попытается
выполнить "fuzzy linking", ища другое определённое имя символа, которое отличается
только по формату имени символа (cdecl vs stdcall), и разрешит этот символ путём
связывания с совпадением. Когда связыватель делает это, он печатает предупреждение,
поскольку нормально связывание должно было потерпеть неудачу, но иногда импортные
библиотеки, генерируемые из сторонних dll, нуждаются в этой функции, чтобы быть
usable. Если вы укажете --enable-stdcall-fixup, эта функция полностью включена
и предупреждения не печатаются. Если вы укажете --disable-stdcall-fixup, эта функция
отключена, и такие несоответствия считаются ошибками. [Эта опция специфична для
целевой платформы i386 PE связывателя]
--leading-underscore
--no-leading-underscore
Для большинства целей префикс символа по умолчанию — подчёркивание и определён
в описании цели. С помощью этой опции возможно отключить/включить префикс символа
по умолчанию.
--export-all-symbols
Если указано, все глобальные символы в объектах, используемых для построения DLL,
будут экспортированы DLL. Замечание, что это значение по умолчанию, если в противном
случае не будет никаких экспортируемых символов. Когда символы явно экспортируются
через файлы DEF или неявно экспортируются через атрибуты функций, значение по
умолчанию — не экспортировать ничего другого, если эта опция не указана. Замечание,
что символы "DllMain@12", "DllEntryPoint@0", "DllMainCRTStartup@12" и "impure_ptr"
не будут автоматически экспортироваться. Кроме того, символы, импортированные из
других DLL, не будут повторно экспортироваться, ни символы, указывающие внутреннюю
структуру DLL, такие как те, что начинаются с "_head_" или заканчиваются "_iname".
Кроме того, никакие символы из "libgcc", "libstd++", "libmingw32" или "crtX.o"
не будут экспортироваться. Символы, имена которых начинаются с "__rtti_" или "__builtin_",
не будут экспортироваться, чтобы помочь с DLL C++. Наконец, существует обширный
список символов cygwin-private, которые не экспортируются (очевидно, это применяется
только при построении DLL для целей cygwin). Эти исключения cygwin — "_cygwin_dll_entry@12",
"_cygwin_crt0_common@8", "_cygwin_noncygwin_dll_entry@12", "_fmode", "_impure_ptr",
"cygwin_attach_dll", "cygwin_premain0", "cygwin_premain1", "cygwin_premain2",
"cygwin_premain3" и "environ". [Эта опция специфична для целевой платформы i386 PE
связывателя]
--exclude-symbols symbol,symbol,...
Указывает список символов, которые не должны автоматически экспортироваться.
Имена символов могут быть разделены запятыми или двоеточиями. [Эта опция специфична
для целевой платформы i386 PE связывателя]
--exclude-all-symbols
Указывает, что никакие символы не должны автоматически экспортироваться. [Эта
опция специфична для целевой платформы i386 PE связывателя]
--file-alignment
Указать выравнивание файла. Разделы в файле всегда будут начинаться по смещениям
файла, которые являются кратными этому числу. Значение по умолчанию — 512. [Эта
опция специфична для целевой платформы i386 PE связывателя]
--heap reserve
--heap reserve,commit
Указать количество байтов памяти для резервирования (и, опционально, фиксации)
для использования как куча для этой программы. Значение по умолчанию — 1MB
зарезервировано, 4K зафиксировано. [Эта опция специфична для целевой платформы
i386 PE связывателя]
--kill-at
Если указано, суффиксы stdcall (@nn) будут удалены из символов перед их экспортом.
[Эта опция специфична для целевой платформы i386 PE связывателя]
--large-address-aware
Если указано, соответствующий бит в поле "Characteristics" заголовка COFF
устанавливается для указания, что этот исполняемый файл поддерживает виртуальные
адреса больше 2 гигабайт. Это следует использовать в сочетании с переключателем
/3GB или /USERVA=value мегабайт в разделе "[operating systems]" файла BOOT.INI.
В противном случае этот бит не имеет эффекта. [Эта опция специфична для целевых
платформ PE связывателя]
--disable-large-address-aware
Отменяет эффект предыдущей опции --large-address-aware. Это полезно, если --large-address-aware
всегда устанавливается драйвером компилятора (например, Cygwin gcc), и исполняемый
файл не поддерживает виртуальные адреса больше 2 гигабайт. [Эта опция специфична
для целевых платформ PE связывателя]
--major-image-version value
Установить основной номер "версии изображения". Значение по умолчанию — 1. [Эта
опция специфична для целевой платформы i386 PE связывателя]
--major-os-version value
Установить основной номер "версии OS". Значение по умолчанию — 4. [Эта опция
специфична для целевой платформы i386 PE связывателя]
--major-subsystem-version value
Установить основной номер "версии подсистемы". Значение по умолчанию — 4. [Эта
опция специфична для целевой платформы i386 PE связывателя]
--minor-image-version value
Установить вспомогательный номер "версии изображения". Значение по умолчанию — 0.
[Эта опция специфична для целевой платформы i386 PE связывателя]
--minor-os-version value
Установить вспомогательный номер "версии OS". Значение по умолчанию — 0. [Эта
опция специфична для целевой платформы i386 PE связывателя]
--minor-subsystem-version value
Установить вспомогательный номер "версии подсистемы". Значение по умолчанию — 0.
[Эта опция специфична для целевой платформы i386 PE связывателя]
--output-def file
Связыватель создаст файл file, который будет содержать файл DEF, соответствующий
DLL, который создаёт связыватель. Этот файл DEF (который должен называться "*.def")
может использоваться для создания импортной библиотеки с "dlltool" или может
использоваться как ссылка на автоматически или неявно экспортируемые символы.
[Эта опция специфична для целевой платформы i386 PE связывателя]
--enable-auto-image-base
--enable-auto-image-base=value
Автоматически выбрать базовый адрес изображения для DLL, опционально начиная
с value, если он не указан с помощью аргумента "--image-base". Используя хэш,
сгенерированный из имени dll, для создания уникальных базовых адресов для каждой
DLL, избегаются коллизии в памяти и релокации, которые могут задерживать выполнение
программы. [Эта опция специфична для целевой платформы i386 PE связывателя]
--disable-auto-image-base
Не автоматически генерировать уникальный базовый адрес изображения. Если нет
пользовательского базового адреса ("--image-base"), то использовать значение по
умолчанию платформы. [Эта опция специфична для целевой платформы i386 PE связывателя]
--dll-search-prefix string
При динамическом связывании с dll без импортной библиотеки искать "<string><basename>.dll"
в предпочтении перед "lib<basename>.dll". Это поведение позволяет легко различать
DLL, построенные для различных "подплатформ": native, cygwin, uwin, pw и т.д.
Например, DLL cygwin обычно используют "--dll-search-prefix=cyg". [Эта опция
специфична для целевой платформы i386 PE связывателя]
--enable-auto-import
Выполнять сложное связывание "_symbol" с "__imp__symbol" для импортов DATA из DLL,
делая возможным обходить механизм dllimport на стороне пользователя и ссылаться
на неманглированные имена символов. [Эта опция специфична для целевой платформы
i386 PE связывателя]
Следующие замечания относятся к оригинальной реализации функции и устарели для
целей Cygwin и MinGW.
Замечание: Использование расширения 'auto-import' заставит раздел текста файла
изображения быть сделанным записываемым. Это не соответствует спецификации формата
PE-COFF, опубликованной Microsoft.
Замечание — использование расширения 'auto-import' также заставит данные только
для чтения, которые обычно помещаются в раздел .rdata, быть размещёнными в разделе
.data вместо этого. Это для обхода проблемы с константами, описанной здесь:
http://www.cygwin.com/ml/cygwin/2004-09/msg01101.html
Использование 'auto-import' в общем случае 'просто сработает' — но иногда вы можете
увидеть это сообщение:
"variable '<var>' can't be auto-imported. Please read the documentation for ld's
"--enable-auto-import" for details."
Это сообщение возникает, когда какое-то (под)выражение обращается к адресу, в конечном
счёте данному суммой двух констант (таблицы импортов Win32 позволяют только одну).
Примеры, где это может произойти, включают обращения к полям членов структурных переменных,
импортированных из DLL, а также использование константного индекса в переменную массива,
импортированную из DLL. Любая многословная переменная (массивы, структуры, long long и т.д.)
может вызвать это условие ошибки. Однако, независимо от точного типа данных проблемного
экспортируемого переменной, ld всегда обнаружит это, выдаст предупреждение и выйдет.
Существуют несколько способов решить эту проблему, независимо от типа данных
экспортируемой переменной:
Один способ — использовать переключатель --enable-runtime-pseudo-reloc. Это оставляет
задачу корректировки ссылок в вашем клиентском коде для среды выполнения, так что
этот метод работает только когда среда выполнения поддерживает эту функцию.
Второе решение — заставить одну из 'констант' быть переменной — то есть, неизвестной
и неоптимизируемой на этапе компиляции. Для массивов есть две возможности: a) сделать
индексируемый (адрес массива) переменной или b) сделать 'константный' индекс переменной.
Таким образом:
extern type extern_array[];
extern_array[1] -->
{ volatile type *t=extern_array; t[1] }
или
extern type extern_array[];
extern_array[1] -->
{ volatile int t=1; extern_array[t] }
Для структур (и большинства других многословных типов данных) единственный вариант —
сделать структуру саму (или long long, или ...) переменной:
extern struct s extern_struct;
extern_struct.field -->
{ volatile struct s *t=&extern_struct; t->field }
или
extern long long extern_ll;
extern_ll -->
{ volatile long long * local_ll=&extern_ll; *local_ll }
Третий метод обработки этой проблемы — отказаться от 'auto-import' для проблемного
символа и пометить его "__declspec(dllimport)". Однако, на практике это требует
использования определений на этапе компиляции #defines для указания, строите ли вы
DLL, строите ли клиентский код, который свяжется с DLL, или просто строите/связываете
со статической библиотекой. При выборе между различными методами разрешения проблемы
'прямой адрес с константным смещением', вы должны учитывать типичное использование
в реальном мире:
Оригинал:
--foo.h
extern int arr[];
--foo.c
#include "foo.h"
void main(int argc, char **argv){
printf("%d\n",arr[1]);
}
Решение 1:
--foo.h
extern int arr[];
--foo.c
#include "foo.h"
void main(int argc, char **argv){
/* This workaround is for win32 and cygwin; do not "optimize" */
volatile int *parr = arr;
printf("%d\n",parr[1]);
}
Решение 2:
--foo.h
/* Note: auto-export is assumed (no __declspec(dllexport)) */
#if (defined(_WIN32) || defined(__CYGWIN__)) && \
!(defined(FOO_BUILD_DLL) || defined(FOO_STATIC))
#define FOO_IMPORT __declspec(dllimport)
#else
#define FOO_IMPORT
#endif
extern FOO_IMPORT int arr[];
--foo.c
#include "foo.h"
void main(int argc, char **argv){
printf("%d\n",arr[1]);
}
Четвёртый способ избежать этой проблемы — переписать вашу библиотеку для использования
функционального интерфейса вместо интерфейса данных для проблемных переменных
(например, функций доступа set_foo() и get_foo()).
--disable-auto-import
Не пытаться выполнять сложное связывание "_symbol" с "__imp__symbol" для импортов
DATA из DLL. [Эта опция специфична для целевой платформы i386 PE связывателя]
--enable-runtime-pseudo-reloc
Если ваш код содержит выражения, описанные в разделе --enable-auto-import, то есть,
импорты DATA из DLL с ненулевым смещением, этот переключатель создаст вектор 'псевдорелокаций
во время выполнения', который может использоваться средой выполнения для корректировки
ссылок на такие данные в вашем клиентском коде. [Эта опция специфична для целевой
платформы i386 PE связывателя]
--disable-runtime-pseudo-reloc
Не создавать псевдорелокации для импортов DATA из DLL с ненулевым смещением.
[Эта опция специфична для целевой платформы i386 PE связывателя]
--enable-extra-pe-debug
Показать дополнительную отладочную информацию, связанную с thunking символов
auto-import. [Эта опция специфична для целевой платформы i386 PE связывателя]
--section-alignment
Установить выравнивание раздела. Разделы в памяти всегда будут начинаться по
адресам, которые являются кратными этому числу. Значение по умолчанию — 0x1000.
[Эта опция специфична для целевой платформы i386 PE связывателя]
--stack reserve
--stack reserve,commit
Указать количество байтов памяти для резервирования (и, опционально, фиксации)
для использования как стек для этой программы. Значение по умолчанию — 2MB
зарезервировано, 4K зафиксировано. [Эта опция специфична для целевой платформы
i386 PE связывателя]
--subsystem which
--subsystem which:major
--subsystem which:major.minor
Указать подсистему, под которой будет выполняться ваша программа. Допустимые
значения для which — "native", "windows", "console", "posix" и "xbox". Вы можете
опционально установить версию подсистемы тоже. Числовые значения также принимаются
для which. [Эта опция специфична для целевой платформы i386 PE связывателя]
Следующие опции устанавливают флаги в поле "DllCharacteristics" заголовка PE-файла:
[Эти опции специфичны для целевых платформ PE связывателя]
--high-entropy-va
--disable-high-entropy-va
Образ совместим с случайной компоновкой адресного пространства 64-битной (ASLR).
Эта опция включена по умолчанию для 64-битных образов PE.
Эта опция также подразумевает --dynamicbase и --enable-reloc-section.
--dynamicbase
--disable-dynamicbase
Базовый адрес изображения может быть перераспределён с использованием случайной
компоновки адресного пространства (ASLR). Эта функция была введена с MS Windows Vista
для целей i386 PE. Эта опция включена по умолчанию, но может быть отключена опцией
--disable-dynamicbase. Эта опция также подразумевает --enable-reloc-section.
--forceinteg
--disable-forceinteg
Проверки целостности кода принудительно выполняются. Эта опция отключена по умолчанию.
--nxcompat
--disable-nxcompat
Образ совместим с предотвращением выполнения данных. Эта функция была введена
с MS Windows XP SP2 для целей i386 PE. Опция включена по умолчанию.
--no-isolation
--disable-no-isolation
Хотя образ понимает изоляцию, не изолировать образ. Эта опция отключена по умолчанию.
--no-seh
--disable-no-seh
Образ не использует SEH. Ни один обработчик SE не может быть вызван из этого
образа. Эта опция отключена по умолчанию.
--no-bind
--disable-no-bind
Не связывать этот образ. Эта опция отключена по умолчанию.
--wdmdriver
--disable-wdmdriver
Драйвер использует модель драйвера MS Windows. Эта опция отключена по умолчанию.
--tsaware
--disable-tsaware
Образ осведомлён о терминальном сервере. Эта опция отключена по умолчанию.
--insert-timestamp
--no-insert-timestamp
Вставить реальное время в образ. Это поведение по умолчанию, так как оно соответствует
устаревшему коду, и это означает, что образ будет работать с другими, проприетарными
инструментами. Проблема с этим значением по умолчанию заключается в том, что это
приведёт к получению слегка разных образов каждый раз, когда одни и те же источники
связываются. Опция --no-insert-timestamp может использоваться для вставки нулевого
значения для времени, обеспечивая, чтобы бинарники, произведённые из идентичных
источников, сравнивались идентично.
Если --insert-timestamp активна, то вставляемое время либо время связывания,
либо, если определена переменная окружения "SOURCE_DATE_EPOCH", количество секунд
с эпохи Unix, указанное этой переменной.
SEE ALSO
ar(1), nm(1), objcopy(1), objdump(1), readelf(1) и записи Info для binutils и ld.
COPYRIGHT
Copyright (c) 1991-2025 Free Software Foundation, Inc.
Разрешается копировать, распространять и/или изменять этот документ в соответствии
с условиями Лицензии GNU Free Documentation License, версии 1.3 или любой
более поздней версии, опубликованной Free Software Foundation; без Инвариантных
Разделов, без Текстов Обложки и без Текстов Обратной Обложки. Копия лицензии
включена в раздел, озаглавленный "GNU Free Documentation License".
LD(1) GNU Development Tools LD(1)
NAME
ld - The GNU linker
SYNOPSIS
ld [options] objfile ...
DESCRIPTION
ld combines a number of object and archive files, relocates their data
and ties up symbol references. Usually the last step in compiling a
program is to run ld.
ld accepts Linker Command Language files written in a superset of
AT&T's Link Editor Command Language syntax, to provide explicit and
total control over the linking process.
This man page does not describe the command language; see the ld entry
in "info" for full details on the command language and on other aspects
of the GNU linker.
This version of ld uses the general purpose BFD libraries to operate on
object files. This allows ld to read, combine, and write object files
in many different formats---for example, COFF or "a.out". Different
formats may be linked together to produce any available kind of object
file.
Aside from its flexibility, the GNU linker is more helpful than other
linkers in providing diagnostic information. Many linkers abandon
execution immediately upon encountering an error; whenever possible, ld
continues executing, allowing you to identify other errors (or, in some
cases, to get an output file in spite of the error).
The GNU linker ld is meant to cover a broad range of situations, and to
be as compatible as possible with other linkers. As a result, you have
many choices to control its behavior.
OPTIONS
The linker supports a plethora of command-line options, but in actual
practice few of them are used in any particular context. For instance,
a frequent use of ld is to link standard Unix object files on a
standard, supported Unix system. On such a system, to link a file
"hello.o":
ld -o <output> /lib/crt0.o hello.o -lc
This tells ld to produce a file called output as the result of linking
the file "/lib/crt0.o" with "hello.o" and the library "libc.a", which
will come from the standard search directories. (See the discussion of
the -l option below.)
Some of the command-line options to ld may be specified at any point in
the command line. However, options which refer to files, such as -l or
-T, cause the file to be read at the point at which the option appears
in the command line, relative to the object files and other file
options. Repeating non-file options with a different argument will
either have no further effect, or override prior occurrences (those
further to the left on the command line) of that option. Options which
may be meaningfully specified more than once are noted in the
descriptions below.
Non-option arguments are object files or archives which are to be
linked together. They may follow, precede, or be mixed in with
command-line options, except that an object file argument may not be
placed between an option and its argument.
Usually the linker is invoked with at least one object file, but you
can specify other forms of binary input files using -l, -R, and the
script command language. If no binary input files at all are
specified, the linker does not produce any output, and issues the
message No input files.
If the linker cannot recognize the format of an object file, it will
assume that it is a linker script. A script specified in this way
augments the main linker script used for the link (either the default
linker script or the one specified by using -T). This feature permits
the linker to link against a file which appears to be an object or an
archive, but actually merely defines some symbol values, or uses
"INPUT" or "GROUP" to load other objects. Specifying a script in this
way merely augments the main linker script, with the extra commands
placed after the main script; use the -T option to replace the default
linker script entirely, but note the effect of the "INSERT" command.
For options whose names are a single letter, option arguments must
either follow the option letter without intervening whitespace, or be
given as separate arguments immediately following the option that
requires them.
For options whose names are multiple letters, either one dash or two
can precede the option name; for example, -trace-symbol and
--trace-symbol are equivalent. Note---there is one exception to this
rule. Multiple letter options that start with a lower case 'o' can
only be preceded by two dashes. This is to reduce confusion with the
-o option. So for example -omagic sets the output file name to magic
whereas --omagic sets the NMAGIC flag on the output.
Arguments to multiple-letter options must either be separated from the
option name by an equals sign, or be given as separate arguments
immediately following the option that requires them. For example,
--trace-symbol foo and --trace-symbol=foo are equivalent. Unique
abbreviations of the names of multiple-letter options are accepted.
Note---if the linker is being invoked indirectly, via a compiler driver
(e.g. gcc) then all the linker command-line options should be prefixed
by -Wl, (or whatever is appropriate for the particular compiler driver)
like this:
gcc -Wl,--start-group foo.o bar.o -Wl,--end-group
This is important, because otherwise the compiler driver program may
silently drop the linker options, resulting in a bad link. Confusion
may also arise when passing options that require values through a
driver, as the use of a space between option and argument acts as a
separator, and causes the driver to pass only the option to the linker
and the argument to the compiler. In this case, it is simplest to use
the joined forms of both single- and multiple-letter options, such as:
gcc foo.o bar.o -Wl,-eENTRY -Wl,-Map=a.map
Here is a table of the generic command-line switches accepted by the
GNU linker:
@file
Read command-line options from file. The options read are inserted
in place of the original @file option. If file does not exist, or
cannot be read, then the option will be treated literally, and not
removed.
Options in file are separated by whitespace. A whitespace
character may be included in an option by surrounding the entire
option in either single or double quotes. Any character (including
a backslash) may be included by prefixing the character to be
included with a backslash. The file may itself contain additional
@file options; any such options will be processed recursively.
-a keyword
This option is supported for HP/UX compatibility. The keyword
argument must be one of the strings archive, shared, or default.
-aarchive is functionally equivalent to -Bstatic, and the other two
keywords are functionally equivalent to -Bdynamic. This option may
be used any number of times.
--audit AUDITLIB
Adds AUDITLIB to the "DT_AUDIT" entry of the dynamic section.
AUDITLIB is not checked for existence, nor will it use the
DT_SONAME specified in the library. If specified multiple times
"DT_AUDIT" will contain a colon separated list of audit interfaces
to use. If the linker finds an object with an audit entry while
searching for shared libraries, it will add a corresponding
"DT_DEPAUDIT" entry in the output file. This option is only
meaningful on ELF platforms supporting the rtld-audit interface.
-b input-format
--format=input-format
ld may be configured to support more than one kind of object file.
If your ld is configured this way, you can use the -b option to
specify the binary format for input object files that follow this
option on the command line. Even when ld is configured to support
alternative object formats, you don't usually need to specify this,
as ld should be configured to expect as a default input format the
most usual format on each machine. input-format is a text string,
the name of a particular format supported by the BFD libraries.
(You can list the available binary formats with objdump -i.)
You may want to use this option if you are linking files with an
unusual binary format. You can also use -b to switch formats
explicitly (when linking object files of different formats), by
including -b input-format before each group of object files in a
particular format.
The default format is taken from the environment variable
"GNUTARGET".
You can also define the input format from a script, using the
command "TARGET";
-c MRI-commandfile
--mri-script=MRI-commandfile
For compatibility with linkers produced by MRI, ld accepts script
files written in an alternate, restricted command language,
described in the MRI Compatible Script Files section of GNU ld
documentation. Introduce MRI script files with the option -c; use
the -T option to run linker scripts written in the general-purpose
ld scripting language. If MRI-cmdfile does not exist, ld looks for
it in the directories specified by any -L options.
-d
-dc
-dp These three options are equivalent; multiple forms are supported
for compatibility with other linkers. They assign space to common
symbols even if a relocatable output file is specified (with -r).
The script command "FORCE_COMMON_ALLOCATION" has the same effect.
--depaudit AUDITLIB
-P AUDITLIB
Adds AUDITLIB to the "DT_DEPAUDIT" entry of the dynamic section.
AUDITLIB is not checked for existence, nor will it use the
DT_SONAME specified in the library. If specified multiple times
"DT_DEPAUDIT" will contain a colon separated list of audit
interfaces to use. This option is only meaningful on ELF platforms
supporting the rtld-audit interface. The -P option is provided for
Solaris compatibility.
--enable-linker-version
Enables the "LINKER_VERSION" linker script directive, described in
Output Section Data. If this directive is used in a linker script
and this option has been enabled then a string containing the
linker version will be inserted at the current point.
Note - this location of this option on the linker command line is
significant. It will only affect linker scripts that come after it
on the command line, or which are built into the linker.
--disable-linker-version
Disables the "LINKER_VERSION" linker script directive, so that it
does not insert a version string. This is the default.
--enable-non-contiguous-regions
This option avoids generating an error if an input section does not
fit a matching output section. The linker tries to allocate the
input section to subseque nt matching output sections, and
generates an error only if no output section is large enough. This
is useful when several non-contiguous memory regions are available
and the input section does not require a particular one. The order
in which input sections are evaluated does not change, for
instance:
MEMORY {
MEM1 (rwx) : ORIGIN = 0x1000, LENGTH = 0x14
MEM2 (rwx) : ORIGIN = 0x1000, LENGTH = 0x40
MEM3 (rwx) : ORIGIN = 0x2000, LENGTH = 0x40
}
SECTIONS {
mem1 : { *(.data.*); } > MEM1
mem2 : { *(.data.*); } > MEM2
mem3 : { *(.data.*); } > MEM3
}
with input sections:
.data.1: size 8
.data.2: size 0x10
.data.3: size 4
results in .data.1 affected to mem1, and .data.2 and .data.3
affected to mem2, even though .data.3 would fit in mem3.
This option is incompatible with INSERT statements because it
changes the way input sections are mapped to output sections.
--enable-non-contiguous-regions-warnings
This option enables warnings when "--enable-non-contiguous-regions"
allows possibly unexpected matches in sections mapping, potentially
leading to silently discarding a section instead of failing because
it does not fit any output region.
-e entry
--entry=entry
Use entry as the explicit symbol for beginning execution of your
program, rather than the default entry point. If there is no
symbol named entry, the linker will try to parse entry as a number,
and use that as the entry address (the number will be interpreted
in base 10; you may use a leading 0x for base 16, or a leading 0
for base 8).
--exclude-libs lib,lib,...
Specifies a list of archive libraries from which symbols should not
be automatically exported. The library names may be delimited by
commas or colons. Specifying "--exclude-libs ALL" excludes symbols
in all archive libraries from automatic export. This option is
available only for the i386 PE targeted port of the linker and for
ELF targeted ports. For i386 PE, symbols explicitly listed in a
.def file are still exported, regardless of this option. For ELF
targeted ports, symbols affected by this option will be treated as
hidden.
--exclude-modules-for-implib module,module,...
Specifies a list of object files or archive members, from which
symbols should not be automatically exported, but which should be
copied wholesale into the import library being generated during the
link. The module names may be delimited by commas or colons, and
must match exactly the filenames used by ld to open the files; for
archive members, this is simply the member name, but for object
files the name listed must include and match precisely any path
used to specify the input file on the linker's command-line. This
option is available only for the i386 PE targeted port of the
linker. Symbols explicitly listed in a .def file are still
exported, regardless of this option.
-E
--export-dynamic
--no-export-dynamic
When creating a dynamically linked executable, using the -E option
or the --export-dynamic option causes the linker to add all symbols
to the dynamic symbol table. The dynamic symbol table is the set
of symbols which are visible from dynamic objects at run time.
If you do not use either of these options (or use the
--no-export-dynamic option to restore the default behavior), the
dynamic symbol table will normally contain only those symbols which
are referenced by some dynamic object mentioned in the link.
If you use "dlopen" to load a dynamic object which needs to refer
back to the symbols defined by the program, rather than some other
dynamic object, then you will probably need to use this option when
linking the program itself.
You can also use the dynamic list to control what symbols should be
added to the dynamic symbol table if the output format supports it.
See the description of --dynamic-list.
Note that this option is specific to ELF targeted ports. PE
targets support a similar function to export all symbols from a DLL
or EXE; see the description of --export-all-symbols below.
--export-dynamic-symbol=glob
When creating a dynamically linked executable, symbols matching
glob will be added to the dynamic symbol table. When creating a
shared library, references to symbols matching glob will not be
bound to the definitions within the shared library. This option is
a no-op when creating a shared library and -Bsymbolic or
--dynamic-list are not specified. This option is only meaningful on
ELF platforms which support shared libraries.
--export-dynamic-symbol-list=file
Specify a --export-dynamic-symbol for each pattern in the file.
The format of the file is the same as the version node without
scope and node name. See VERSION for more information.
-EB Link big-endian objects. This affects the default output format.
-EL Link little-endian objects. This affects the default output
format.
-f name
--auxiliary=name
When creating an ELF shared object, set the internal DT_AUXILIARY
field to the specified name. This tells the dynamic linker that
the symbol table of the shared object should be used as an
auxiliary filter on the symbol table of the shared object name.
If you later link a program against this filter object, then, when
you run the program, the dynamic linker will see the DT_AUXILIARY
field. If the dynamic linker resolves any symbols from the filter
object, it will first check whether there is a definition in the
shared object name. If there is one, it will be used instead of
the definition in the filter object. The shared object name need
not exist. Thus the shared object name may be used to provide an
alternative implementation of certain functions, perhaps for
debugging or for machine-specific performance.
This option may be specified more than once. The DT_AUXILIARY
entries will be created in the order in which they appear on the
command line.
-F name
--filter=name
When creating an ELF shared object, set the internal DT_FILTER
field to the specified name. This tells the dynamic linker that
the symbol table of the shared object which is being created should
be used as a filter on the symbol table of the shared object name.
If you later link a program against this filter object, then, when
you run the program, the dynamic linker will see the DT_FILTER
field. The dynamic linker will resolve symbols according to the
symbol table of the filter object as usual, but it will actually
link to the definitions found in the shared object name. Thus the
filter object can be used to select a subset of the symbols
provided by the object name.
Some older linkers used the -F option throughout a compilation
toolchain for specifying object-file format for both input and
output object files. The GNU linker uses other mechanisms for this
purpose: the -b, --format, --oformat options, the "TARGET" command
in linker scripts, and the "GNUTARGET" environment variable. The
GNU linker will ignore the -F option when not creating an ELF
shared object.
-fini=name
When creating an ELF executable or shared object, call NAME when
the executable or shared object is unloaded, by setting DT_FINI to
the address of the function. By default, the linker uses "_fini"
as the function to call.
-g Ignored. Provided for compatibility with other tools.
-G value
--gpsize=value
Set the maximum size of objects to be optimized using the GP
register to size. This is only meaningful for object file formats
such as MIPS ELF that support putting large and small objects into
different sections. This is ignored for other object file formats.
-h name
-soname=name
When creating an ELF shared object, set the internal DT_SONAME
field to the specified name. When an executable is linked with a
shared object which has a DT_SONAME field, then when the executable
is run the dynamic linker will attempt to load the shared object
specified by the DT_SONAME field rather than using the file name
given to the linker.
-i Perform an incremental link (same as option -r).
-init=name
When creating an ELF executable or shared object, call NAME when
the executable or shared object is loaded, by setting DT_INIT to
the address of the function. By default, the linker uses "_init"
as the function to call.
-l namespec
--library=namespec
Add the archive or object file specified by namespec to the list of
files to link. This option may be used any number of times. If
namespec is of the form :filename, ld will search the library path
for a file called filename, otherwise it will search the library
path for a file called libnamespec.a.
On systems which support shared libraries, ld may also search for
files other than libnamespec.a. Specifically, on ELF and SunOS
systems, ld will search a directory for a library called
libnamespec.so before searching for one called libnamespec.a. (By
convention, a ".so" extension indicates a shared library.) Note
that this behavior does not apply to :filename, which always
specifies a file called filename.
The linker will search an archive only once, at the location where
it is specified on the command line. If the archive defines a
symbol which was undefined in some object which appeared before the
archive on the command line, the linker will include the
appropriate file(s) from the archive. However, an undefined symbol
in an object appearing later on the command line will not cause the
linker to search the archive again.
See the -( option for a way to force the linker to search archives
multiple times.
You may list the same archive multiple times on the command line.
This type of archive searching is standard for Unix linkers.
However, if you are using ld on AIX, note that it is different from
the behaviour of the AIX linker.
-L searchdir
--library-path=searchdir
Add path searchdir to the list of paths that ld will search for
archive libraries and ld control scripts. You may use this option
any number of times. The directories are searched in the order in
which they are specified on the command line. Directories
specified on the command line are searched before the default
directories. All -L options apply to all -l options, regardless of
the order in which the options appear. -L options do not affect
how ld searches for a linker script unless -T option is specified.
If searchdir begins with "=" or $SYSROOT, then this prefix will be
replaced by the sysroot prefix, controlled by the --sysroot option,
or specified when the linker is configured.
The default set of paths searched (without being specified with -L)
depends on which emulation mode ld is using, and in some cases also
on how it was configured.
The paths can also be specified in a link script with the
"SEARCH_DIR" command. Directories specified this way are searched
at the point in which the linker script appears in the command
line.
-m emulation
Emulate the emulation linker. You can list the available
emulations with the --verbose or -V options.
If the -m option is not used, the emulation is taken from the
"LDEMULATION" environment variable, if that is defined.
Otherwise, the default emulation depends upon how the linker was
configured.
--remap-inputs=pattern=filename
--remap-inputs-file=file
These options allow the names of input files to be changed before
the linker attempts to open them. The option
--remap-inputs=foo.o=bar.o will cause any attempt to load a file
called foo.o to instead try to load a file called bar.o. Wildcard
patterns are permitted in the first filename, so
--remap-inputs=foo*.o=bar.o will rename any input file that matches
foo*.o to bar.o.
An alternative form of the option --remap-inputs-file=filename
allows the remappings to be read from a file. Each line in the
file can contain a single remapping. Blank lines are ignored.
Anything from a hash character (#) to the end of a line is
considered to be a comment and is also ignored. The mapping
pattern can be separated from the filename by whitespace or an
equals (=) character.
The options can be specified multiple times. Their contents
accumulate. The remappings will be processed in the order in which
they occur on the command line, and if they come from a file, in
the order in which they occur in the file. If a match is made, no
further checking for that filename will be performed.
If the replacement filename is /dev/null or just NUL then the
remapping will actually cause the input file to be ignored. This
can be a convenient way to experiment with removing input files
from a complicated build environment.
Note that this option is position dependent and only affects
filenames that come after it on the command line. Thus:
ld foo.o --remap-inputs=foo.o=bar.o
Will have no effect, whereas:
ld --remap-inputs=foo.o=bar.o foo.o
Will rename the input file foo.o to bar.o.
Note - these options also affect files referenced by INPUT
statements in linker scripts. But since linker scripts are
processed after the entire command line is read, the position of
the remap options on the command line is not significant.
If the verbose option is enabled then any mappings that match will
be reported, although again the verbose option needs to be enabled
on the command line before the remaped filenames appear.
If the -Map or --print-map options are enabled then the remapping
list will be included in the map output.
-M
--print-map
Print a link map to the standard output. A link map provides
information about the link, including the following:
• Where object files are mapped into memory.
• How common symbols are allocated.
• All archive members included in the link, with a mention of the
symbol which caused the archive member to be brought in.
• The values assigned to symbols.
Note - symbols whose values are computed by an expression which
involves a reference to a previous value of the same symbol may
not have correct result displayed in the link map. This is
because the linker discards intermediate results and only
retains the final value of an expression. Under such
circumstances the linker will display the final value enclosed
by square brackets. Thus for example a linker script
containing:
foo = 1
foo = foo * 4
foo = foo + 8
will produce the following output in the link map if the -M
option is used:
0x00000001 foo = 0x1
[0x0000000c] foo = (foo * 0x4)
[0x0000000c] foo = (foo + 0x8)
See Expressions for more information about expressions in
linker scripts.
• How GNU properties are merged.
When the linker merges input .note.gnu.property sections into
one output .note.gnu.property section, some properties are
removed or updated. These actions are reported in the link
map. For example:
Removed property 0xc0000002 to merge foo.o (0x1) and bar.o (not found)
This indicates that property 0xc0000002 is removed from output
when merging properties in foo.o, whose property 0xc0000002
value is 0x1, and bar.o, which doesn't have property
0xc0000002.
Updated property 0xc0010001 (0x1) to merge foo.o (0x1) and bar.o (0x1)
This indicates that property 0xc0010001 value is updated to 0x1
in output when merging properties in foo.o, whose 0xc0010001
property value is 0x1, and bar.o, whose 0xc0010001 property
value is 0x1.
• On some ELF targets, a list of fixups inserted by --relax
foo.o: Adjusting branch at 0x00000008 towards "far" in section .text
This indicates that the branch at 0x00000008 in foo.o,
targeting the symbol "far" in section .text, has been replaced
by a trampoline.
--print-map-discarded
--no-print-map-discarded
Print (or do not print) the list of discarded and garbage collected
sections in the link map. Enabled by default.
--print-map-locals
--no-print-map-locals
Print (or do not print) local symbols in the link map. Local
symbols will have the text (local) printed before their name, and
will be listed after all of the global symbols in a given section.
Temporary local symbols (typically those that start with .L) will
not be included in the output. Disabled by default.
-n
--nmagic
Turn off page alignment of sections, and disable linking against
shared libraries. If the output format supports Unix style magic
numbers, mark the output as "NMAGIC".
-N
--omagic
Set the text and data sections to be readable and writable. Also,
do not page-align the data segment, and disable linking against
shared libraries. If the output format supports Unix style magic
numbers, mark the output as "OMAGIC". Note: Although a writable
text section is allowed for PE-COFF targets, it does not conform to
the format specification published by Microsoft.
--no-omagic
This option negates most of the effects of the -N option. It sets
the text section to be read-only, and forces the data segment to be
page-aligned. Note - this option does not enable linking against
shared libraries. Use -Bdynamic for this.
-o output
--output=output
Use output as the name for the program produced by ld; if this
option is not specified, the name a.out is used by default. The
script command "OUTPUT" can also specify the output file name.
Note - the linker will delete the output file before it starts to
write to it. It will do this even if it turns out that the link
cannot be completed due to errors.
Note - the linker will check to make sure that the output file name
does not match the name of any of the input files, but that is all.
In particular it will not complain if the output file might
overwrite a source file or some other important file. Therefore in
build systems it is recommended to use the -o option as the last
option on the linker command line. For example consider:
ld -o $(EXE) $(OBJS)
ld $(OBJS) -o $(EXE)
If the EXE variable is not defined for some reason, the first
version of the linker command could end up deleting one of the
object files (the first one in the OBJS list) whereas the second
version of the linker command will generate an error message and
not delete anything.
--dependency-file=depfile
Write a dependency file to depfile. This file contains a rule
suitable for "make" describing the output file and all the input
files that were read to produce it. The output is similar to the
compiler's output with -M -MP. Note that there is no option like
the compiler's -MM, to exclude "system files" (which is not a
well-specified concept in the linker, unlike "system headers" in
the compiler). So the output from --dependency-file is always
specific to the exact state of the installation where it was
produced, and should not be copied into distributed makefiles
without careful editing.
-O level
If level is a numeric values greater than zero ld optimizes the
output. This might take significantly longer and therefore
probably should only be enabled for the final binary. At the
moment this option only affects ELF shared library generation.
Future releases of the linker may make more use of this option.
Also currently there is no difference in the linker's behaviour for
different non-zero values of this option. Again this may change
with future releases.
-plugin name
Involve a plugin in the linking process. The name parameter is the
absolute filename of the plugin. Usually this parameter is
automatically added by the complier, when using link time
optimization, but users can also add their own plugins if they so
wish.
Note that the location of the compiler originated plugins is
different from the place where the ar, nm and ranlib programs
search for their plugins. In order for those commands to make use
of a compiler based plugin it must first be copied into the
${libdir}/bfd-plugins directory. All gcc based linker plugins are
backward compatible, so it is sufficient to just copy in the newest
one.
--push-state
The --push-state allows one to preserve the current state of the
flags which govern the input file handling so that they can all be
restored with one corresponding --pop-state option.
The option which are covered are: -Bdynamic, -Bstatic, -dn, -dy,
-call_shared, -non_shared, -static, -N, -n, --whole-archive,
--no-whole-archive, -r, -Ur, --copy-dt-needed-entries,
--no-copy-dt-needed-entries, --as-needed, --no-as-needed, and -a.
One target for this option are specifications for pkg-config. When
used with the --libs option all possibly needed libraries are
listed and then possibly linked with all the time. It is better to
return something as follows:
-Wl,--push-state,--as-needed -libone -libtwo -Wl,--pop-state
--pop-state
Undoes the effect of --push-state, restores the previous values of
the flags governing input file handling.
-q
--emit-relocs
Leave relocation sections and contents in fully linked executables.
Post link analysis and optimization tools may need this information
in order to perform correct modifications of executables. This
results in larger executables.
This option is currently only supported on ELF platforms.
--force-dynamic
Force the output file to have dynamic sections. This option is
specific to VxWorks targets.
-r
--relocatable
Generate relocatable output---i.e., generate an output file that
can in turn serve as input to ld. This is often called partial
linking. As a side effect, in environments that support standard
Unix magic numbers, this option also sets the output file's magic
number to "OMAGIC". If this option is not specified, an absolute
file is produced. When linking C++ programs, this option will not
resolve references to constructors; to do that, use -Ur.
When an input file does not have the same format as the output
file, partial linking is only supported if that input file does not
contain any relocations. Different output formats can have further
restrictions; for example some "a.out"-based formats do not support
partial linking with input files in other formats at all.
When the relocatable output contains both contents which require
link-time optimization (LTO) and contents which don't require LTO,
a .gnu_object_only section will be created to contain a relocatable
object file, as if -r is applied to all relocatable inputs which
don't require LTO. When processing a relocatable input with a
.gnu_object_only section, the linker will extract the
.gnu_object_only section as a separate input.
Note that since -r groups some sections from different input files
together, there may be negative impacts on code size and locality
in final executable or shared library.
This option does the same thing as -i.
-R filename
--just-symbols=filename
Read symbol names and their addresses from filename, but do not
relocate it or include it in the output. This allows your output
file to refer symbolically to absolute locations of memory defined
in other programs. You may use this option more than once.
For compatibility with other ELF linkers, if the -R option is
followed by a directory name, rather than a file name, it is
treated as the -rpath option.
--rosegment
--no-rosegment
Attempt to ensure that only a single read-only, non-code segment is
created. Only useful when used in conjunction with the -z
separate-code option. The resulting binaries should be smaller
than if -z separate-code is used on its own. Without this option,
or if --no-rosegment is specified, the -z separate-code option will
create two read-only segments, one before the code segment and one
after it.
The name of the options are misleading, but they have been chosen
in order for the linker to be compatible with the LLD and GOLD
linkers.
Thse options are only supported by ELF targets.
-s
--strip-all
Omit all symbol information from the output file.
-S
--strip-debug
Omit debugger symbol information (but not all symbols) from the
output file.
--strip-discarded
--no-strip-discarded
Omit (or do not omit) global symbols defined in discarded sections.
Enabled by default.
-plugin-save-temps
Store the plugin "temporary" intermediate files permanently.
-t
--trace
Print the names of the input files as ld processes them. If -t is
given twice then members within archives are also printed. -t
output is useful to generate a list of all the object files and
scripts involved in linking, for example, when packaging files for
a linker bug report.
-T scriptfile
--script=scriptfile
Use scriptfile as the linker script. This script replaces ld's
default linker script (rather than adding to it), unless the script
contains "INSERT", so commandfile must specify everything necessary
to describe the output file.
If scriptfile does not exist in the current directory, "ld" looks
for it in the directories specified by any preceding -L options.
Command line options that appear before the -T option can affect
the script, but command line options that appear after it do not.
Multiple -T options will accumulate if they are augmenting the
current script, otherwise the last, non-augmenting, -T option will
be used.
There are other ways of specifying linker scripts. See
-dT scriptfile
--default-script=scriptfile
Use scriptfile as the default linker script.
This option is similar to the --script option except that
processing of the script is delayed until after the rest of the
command line has been processed. This allows options placed after
the --default-script option on the command line to affect the
behaviour of the linker script, which can be important when the
linker command line cannot be directly controlled by the user. (eg
because the command line is being constructed by another tool, such
as gcc).
-u symbol
--undefined=symbol
Force symbol to be entered in the output file as an undefined
symbol. Doing this may, for example, trigger linking of additional
modules from standard libraries. -u may be repeated with different
option arguments to enter additional undefined symbols. This
option is equivalent to the "EXTERN" linker script command.
If this option is being used to force additional modules to be
pulled into the link, and if it is an error for the symbol to
remain undefined, then the option --require-defined should be used
instead.
--require-defined=symbol
Require that symbol is defined in the output file. This option is
the same as option --undefined except that if symbol is not defined
in the output file then the linker will issue an error and exit.
The same effect can be achieved in a linker script by using
"EXTERN", "ASSERT" and "DEFINED" together. This option can be used
multiple times to require additional symbols.
-Ur For programs that do not use constructors or destructors, or for
ELF based systems this option is equivalent to -r: it generates
relocatable output---i.e., an output file that can in turn serve as
input to ld. For other binaries however the -Ur option is similar
to -r but it also resolves references to constructors and
destructors.
For those systems where -r and -Ur behave differently, it does not
work to use -Ur on files that were themselves linked with -Ur; once
the constructor table has been built, it cannot be added to. Use
-Ur only for the last partial link, and -r for the others.
--orphan-handling=MODE
Control how orphan sections are handled. An orphan section is one
not specifically mentioned in a linker script.
MODE can have any of the following values:
"place"
Orphan sections are placed into a suitable output section
following the strategy described in Orphan Sections. The
option --unique also affects how sections are placed.
"discard"
All orphan sections are discarded, by placing them in the
/DISCARD/ section.
"warn"
The linker will place the orphan section as for "place" and
also issue a warning.
"error"
The linker will exit with an error if any orphan section is
found.
The default if --orphan-handling is not given is "place".
--unique[=SECTION]
Creates a separate output section for every input section matching
SECTION, or if the optional wildcard SECTION argument is missing,
for every orphan input section. An orphan section is one not
specifically mentioned in a linker script. You may use this option
multiple times on the command line; It prevents the normal merging
of input sections with the same name, overriding output section
assignments in a linker script.
-v
--version
-V Display the version number for ld. The -V option also lists the
supported emulations. See also the description of the
--enable-linker-version in Options,,Command-line Options which can
be used to insert the linker version string into a binary.
-x
--discard-all
Delete all local symbols.
-X
--discard-locals
Delete all temporary local symbols. (These symbols start with
system-specific local label prefixes, typically .L for ELF systems
or L for traditional a.out systems.)
-y symbol
--trace-symbol=symbol
Print the name of each linked file in which symbol appears. This
option may be given any number of times. On many systems it is
necessary to prepend an underscore.
This option is useful when you have an undefined symbol in your
link but don't know where the reference is coming from.
-Y path
Add path to the default library search path. This option exists
for Solaris compatibility.
-z keyword
The recognized keywords are:
call-nop=prefix-addr
call-nop=suffix-nop
call-nop=prefix-byte
call-nop=suffix-byte
Specify the 1-byte "NOP" padding when transforming indirect
call to a locally defined function, foo, via its GOT slot.
call-nop=prefix-addr generates "0x67 call foo".
call-nop=suffix-nop generates "call foo 0x90".
call-nop=prefix-byte generates "byte call foo".
call-nop=suffix-byte generates "call foo byte". Supported for
i386 and x86_64.
cet-report=none
cet-report=warning
cet-report=error
Specify how to report the missing
GNU_PROPERTY_X86_FEATURE_1_IBT and
GNU_PROPERTY_X86_FEATURE_1_SHSTK properties in input
.note.gnu.property section. cet-report=none, which is the
default, will make the linker not report missing properties in
input files. cet-report=warning will make the linker issue a
warning for missing properties in input files.
cet-report=error will make the linker issue an error for
missing properties in input files. Note that ibt will turn off
the missing GNU_PROPERTY_X86_FEATURE_1_IBT property report and
shstk will turn off the missing
GNU_PROPERTY_X86_FEATURE_1_SHSTK property report. Supported
for Linux/i386 and Linux/x86_64.
combreloc
nocombreloc
Combine multiple dynamic relocation sections and sort to
improve dynamic symbol lookup caching. Do not do this if
nocombreloc.
common
nocommon
Generate common symbols with STT_COMMON type during a
relocatable link. Use STT_OBJECT type if nocommon.
common-page-size=value
Set the page size most commonly used to value. Memory image
layout will be optimized to minimize memory pages if the system
is using pages of this size.
defs
Report unresolved symbol references from regular object files.
This is done even if the linker is creating a non-symbolic
shared library. This option is the inverse of -z undefs.
dynamic-undefined-weak
nodynamic-undefined-weak
Make undefined weak symbols dynamic when building a dynamic
object, if they are referenced from a regular object file and
not forced local by symbol visibility or versioning. Do not
make them dynamic if nodynamic-undefined-weak. If neither
option is given, a target may default to either option being in
force, or make some other selection of undefined weak symbols
dynamic. Not all targets support these options.
execstack
Marks the object as requiring executable stack.
global
This option is only meaningful when building a shared object.
It makes the symbols defined by this shared object available
for symbol resolution of subsequently loaded libraries.
globalaudit
This option is only meaningful when building a dynamic
executable. This option marks the executable as requiring
global auditing by setting the "DF_1_GLOBAUDIT" bit in the
"DT_FLAGS_1" dynamic tag. Global auditing requires that any
auditing library defined via the --depaudit or -P command-line
options be run for all dynamic objects loaded by the
application.
ibtplt
Generate Intel Indirect Branch Tracking (IBT) enabled PLT
entries. Supported for Linux/i386 and Linux/x86_64.
ibt Generate GNU_PROPERTY_X86_FEATURE_1_IBT in .note.gnu.property
section to indicate compatibility with IBT. This also implies
ibtplt. Supported for Linux/i386 and Linux/x86_64.
indirect-extern-access
noindirect-extern-access
Generate GNU_PROPERTY_1_NEEDED_INDIRECT_EXTERN_ACCESS in
.note.gnu.property section to indicate that object file
requires canonical function pointers and cannot be used with
copy relocation. This option also implies
noextern-protected-data and nocopyreloc. Supported for i386
and x86-64.
noindirect-extern-access removes
GNU_PROPERTY_1_NEEDED_INDIRECT_EXTERN_ACCESS from
.note.gnu.property section.
initfirst
This option is only meaningful when building a shared object.
It marks the object so that its runtime initialization will
occur before the runtime initialization of any other objects
brought into the process at the same time. Similarly the
runtime finalization of the object will occur after the runtime
finalization of any other objects.
interpose
Specify that the dynamic loader should modify its symbol search
order so that symbols in this shared library interpose all
other shared libraries not so marked.
unique
nounique
When generating a shared library or other dynamically loadable
ELF object mark it as one that should (by default) only ever be
loaded once, and only in the main namespace (when using
"dlmopen"). This is primarily used to mark fundamental
libraries such as libc, libpthread et al which do not usually
function correctly unless they are the sole instances of
themselves. This behaviour can be overridden by the "dlmopen"
caller and does not apply to certain loading mechanisms (such
as audit libraries).
lam-u48
Generate GNU_PROPERTY_X86_FEATURE_1_LAM_U48 in
.note.gnu.property section to indicate compatibility with Intel
LAM_U48. Supported for Linux/x86_64.
lam-u57
Generate GNU_PROPERTY_X86_FEATURE_1_LAM_U57 in
.note.gnu.property section to indicate compatibility with Intel
LAM_U57. Supported for Linux/x86_64.
lam-u48-report=none
lam-u48-report=warning
lam-u48-report=error
Specify how to report the missing
GNU_PROPERTY_X86_FEATURE_1_LAM_U48 property in input
.note.gnu.property section. lam-u48-report=none, which is the
default, will make the linker not report missing properties in
input files. lam-u48-report=warning will make the linker issue
a warning for missing properties in input files.
lam-u48-report=error will make the linker issue an error for
missing properties in input files. Supported for Linux/x86_64.
lam-u57-report=none
lam-u57-report=warning
lam-u57-report=error
Specify how to report the missing
GNU_PROPERTY_X86_FEATURE_1_LAM_U57 property in input
.note.gnu.property section. lam-u57-report=none, which is the
default, will make the linker not report missing properties in
input files. lam-u57-report=warning will make the linker issue
a warning for missing properties in input files.
lam-u57-report=error will make the linker issue an error for
missing properties in input files. Supported for Linux/x86_64.
lam-report=none
lam-report=warning
lam-report=error
Specify how to report the missing
GNU_PROPERTY_X86_FEATURE_1_LAM_U48 and
GNU_PROPERTY_X86_FEATURE_1_LAM_U57 properties in input
.note.gnu.property section. lam-report=none, which is the
default, will make the linker not report missing properties in
input files. lam-report=warning will make the linker issue a
warning for missing properties in input files.
lam-report=error will make the linker issue an error for
missing properties in input files. Supported for Linux/x86_64.
lazy
When generating an executable or shared library, mark it to
tell the dynamic linker to defer function call resolution to
the point when the function is called (lazy binding), rather
than at load time. Lazy binding is the default.
loadfltr
Specify that the object's filters be processed immediately at
runtime.
max-page-size=value
Set the maximum memory page size supported to value.
mark-plt
nomark-plt
Mark PLT entries with dynamic tags, DT_X86_64_PLT,
DT_X86_64_PLTSZ and DT_X86_64_PLTENT. Since this option stores
a non-zero value in the r_addend field of R_X86_64_JUMP_SLOT
relocations, the resulting executables and shared libraries are
incompatible with dynamic linkers, such as those in older
versions of glibc without the change to ignore r_addend in
R_X86_64_GLOB_DAT and R_X86_64_JUMP_SLOT relocations, which
don't ignore the r_addend field of R_X86_64_JUMP_SLOT
relocations. Supported for x86_64.
muldefs
Allow multiple definitions.
nocopyreloc
Disable linker generated .dynbss variables used in place of
variables defined in shared libraries. May result in dynamic
text relocations.
nodefaultlib
Specify that the dynamic loader search for dependencies of this
object should ignore any default library search paths.
nodelete
Specify that the object shouldn't be unloaded at runtime.
nodlopen
Specify that the object is not available to "dlopen".
nodump
Specify that the object can not be dumped by "dldump".
noexecstack
Marks the object as not requiring executable stack.
noextern-protected-data
Don't treat protected data symbols as external when building a
shared library. This option overrides the linker backend
default. It can be used to work around incorrect relocations
against protected data symbols generated by compiler. Updates
on protected data symbols by another module aren't visible to
the resulting shared library. Supported for i386 and x86-64.
noreloc-overflow
Disable relocation overflow check. This can be used to disable
relocation overflow check if there will be no dynamic
relocation overflow at run-time. Supported for x86_64.
memory-seal
nomemory-seal
Instruct the executable or shared library that the all PT_LOAD
segments should be sealed to avoid further manipulation (such
as changing the protection flags, the segment size, or remove
the mapping). This is a security hardening that requires
system support. This generates GNU_PROPERTY_MEMORY_SEAL in
.note.gnu.property section
now When generating an executable or shared library, mark it to
tell the dynamic linker to resolve all symbols when the program
is started, or when the shared library is loaded by dlopen,
instead of deferring function call resolution to the point when
the function is first called.
origin
Specify that the object requires $ORIGIN handling in paths.
pack-relative-relocs
nopack-relative-relocs
Generate compact relative relocation in position-independent
executable and shared library. It adds "DT_RELR", "DT_RELRSZ"
and "DT_RELRENT" entries to the dynamic section. It is ignored
when building position-dependent executable and relocatable
output. nopack-relative-relocs is the default, which disables
compact relative relocation. When linked against the GNU C
Library, a GLIBC_ABI_DT_RELR symbol version dependency on the
shared C Library is added to the output. Supported for i386
and x86-64.
relro
norelro
Create an ELF "PT_GNU_RELRO" segment header in the object.
This specifies a memory segment that should be made read-only
after relocation, if supported. Specifying common-page-size
smaller than the system page size will render this protection
ineffective. Don't create an ELF "PT_GNU_RELRO" segment if
norelro.
report-relative-reloc
Report dynamic relative relocations generated by linker.
Supported for Linux/i386 and Linux/x86_64.
sectionheader
nosectionheader
Generate section header. Don't generate section header if
nosectionheader is used. sectionheader is the default.
separate-code
noseparate-code
Create separate code "PT_LOAD" segment header in the object.
This specifies a memory segment that should contain only
instructions and must be in wholly disjoint pages from any
other data. Don't create separate code "PT_LOAD" segment if
noseparate-code is used.
shstk
Generate GNU_PROPERTY_X86_FEATURE_1_SHSTK in .note.gnu.property
section to indicate compatibility with Intel Shadow Stack.
Supported for Linux/i386 and Linux/x86_64.
stack-size=value
Specify a stack size for an ELF "PT_GNU_STACK" segment.
Specifying zero will override any default non-zero sized
"PT_GNU_STACK" segment creation.
start-stop-gc
nostart-stop-gc
When --gc-sections is in effect, a reference from a retained
section to "__start_SECNAME" or "__stop_SECNAME" causes all
input sections named "SECNAME" to also be retained, if
"SECNAME" is representable as a C identifier and either
"__start_SECNAME" or "__stop_SECNAME" is synthesized by the
linker. -z start-stop-gc disables this effect, allowing
sections to be garbage collected as if the special synthesized
symbols were not defined. -z start-stop-gc has no effect on a
definition of "__start_SECNAME" or "__stop_SECNAME" in an
object file or linker script. Such a definition will prevent
the linker providing a synthesized "__start_SECNAME" or
"__stop_SECNAME" respectively, and therefore the special
treatment by garbage collection for those references.
start-stop-visibility=value
Specify the ELF symbol visibility for synthesized
"__start_SECNAME" and "__stop_SECNAME" symbols. value must be
exactly default, internal, hidden, or protected. If no -z
start-stop-visibility option is given, protected is used for
compatibility with historical practice. However, it's highly
recommended to use -z start-stop-visibility=hidden in new
programs and shared libraries so that these symbols are not
exported between shared objects, which is not usually what's
intended.
text
notext
textoff
Report an error if DT_TEXTREL is set, i.e., if the
position-independent or shared object has dynamic relocations
in read-only sections. Don't report an error if notext or
textoff.
undefs
Do not report unresolved symbol references from regular object
files, either when creating an executable, or when creating a
shared library. This option is the inverse of -z defs.
unique-symbol
nounique-symbol
Avoid duplicated local symbol names in the symbol string table.
Append "."number"" to duplicated local symbol names if
unique-symbol is used. nounique-symbol is the default.
x86-64-baseline
x86-64-v2
x86-64-v3
x86-64-v4
Specify the x86-64 ISA level needed in .note.gnu.property
section. x86-64-baseline generates
"GNU_PROPERTY_X86_ISA_1_BASELINE". x86-64-v2 generates
"GNU_PROPERTY_X86_ISA_1_V2". x86-64-v3 generates
"GNU_PROPERTY_X86_ISA_1_V3". x86-64-v4 generates
"GNU_PROPERTY_X86_ISA_1_V4". Supported for Linux/i386 and
Linux/x86_64.
isa-level-report=none
isa-level-report=all
isa-level-report=needed
isa-level-report=used
Specify how to report x86-64 ISA levels in input relocatable
files. isa-level-report=none, which is the default, will make
the linker not report x86-64 ISA levels in input files.
isa-level-report=all will make the linker report needed and
used x86-64 ISA levels in input files. isa-level-report=needed
will make the linker report needed x86-64 ISA levels in input
files. isa-level-report=used will make the linker report used
x86-64 ISA levels in input files. Supported for Linux/i386 and
Linux/x86_64.
Other keywords are ignored for Solaris compatibility.
-( archives -)
--start-group archives --end-group
The archives should be a list of archive files. They may be either
explicit file names, or -l options.
The specified archives are searched repeatedly until no new
undefined references are created. Normally, an archive is searched
only once in the order that it is specified on the command line.
If a symbol in that archive is needed to resolve an undefined
symbol referred to by an object in an archive that appears later on
the command line, the linker would not be able to resolve that
reference. By grouping the archives, they will all be searched
repeatedly until all possible references are resolved.
Using this option has a significant performance cost. It is best
to use it only when there are unavoidable circular references
between two or more archives.
--accept-unknown-input-arch
--no-accept-unknown-input-arch
Tells the linker to accept input files whose architecture cannot be
recognised. The assumption is that the user knows what they are
doing and deliberately wants to link in these unknown input files.
This was the default behaviour of the linker, before release 2.14.
The default behaviour from release 2.14 onwards is to reject such
input files, and so the --accept-unknown-input-arch option has been
added to restore the old behaviour.
--as-needed
--no-as-needed
This option affects ELF DT_NEEDED tags for dynamic libraries
mentioned on the command line after the --as-needed option.
Normally the linker will add a DT_NEEDED tag for each dynamic
library mentioned on the command line, regardless of whether the
library is actually needed or not. --as-needed causes a DT_NEEDED
tag to only be emitted for a library that at that point in the link
satisfies a non-weak undefined symbol reference from a regular
object file or, if the library is not found in the DT_NEEDED lists
of other needed libraries, a non-weak undefined symbol reference
from another needed dynamic library. Object files or libraries
appearing on the command line after the library in question do not
affect whether the library is seen as needed. This is similar to
the rules for extraction of object files from archives.
--no-as-needed restores the default behaviour.
Note: On Linux based systems the --as-needed option also has an
affect on the behaviour of the --rpath and --rpath-link options.
See the description of --rpath-link for more details.
--add-needed
--no-add-needed
These two options have been deprecated because of the similarity of
their names to the --as-needed and --no-as-needed options. They
have been replaced by --copy-dt-needed-entries and
--no-copy-dt-needed-entries.
-assert keyword
This option is ignored for SunOS compatibility.
-Bdynamic
-dy
-call_shared
Link against dynamic libraries. This is only meaningful on
platforms for which shared libraries are supported. This option is
normally the default on such platforms. The different variants of
this option are for compatibility with various systems. You may
use this option multiple times on the command line: it affects
library searching for -l options which follow it.
-Bgroup
Set the "DF_1_GROUP" flag in the "DT_FLAGS_1" entry in the dynamic
section. This causes the runtime linker to handle lookups in this
object and its dependencies to be performed only inside the group.
--unresolved-symbols=report-all is implied. This option is only
meaningful on ELF platforms which support shared libraries.
-Bstatic
-dn
-non_shared
-static
Do not link against shared libraries. This is only meaningful on
platforms for which shared libraries are supported. The different
variants of this option are for compatibility with various systems.
You may use this option multiple times on the command line: it
affects library searching for -l options which follow it. This
option also implies --unresolved-symbols=report-all. This option
can be used with -shared. Doing so means that a shared library is
being created but that all of the library's external references
must be resolved by pulling in entries from static libraries.
-Bsymbolic
When creating a shared library, bind references to global symbols
to the definition within the shared library, if any. Normally, it
is possible for a program linked against a shared library to
override the definition within the shared library. This option is
only meaningful on ELF platforms which support shared libraries.
-Bsymbolic-functions
When creating a shared library, bind references to global function
symbols to the definition within the shared library, if any. This
option is only meaningful on ELF platforms which support shared
libraries.
-Bno-symbolic
This option can cancel previously specified -Bsymbolic and
-Bsymbolic-functions.
--dynamic-list=dynamic-list-file
Specify the name of a dynamic list file to the linker. This is
typically used when creating shared libraries to specify a list of
global symbols whose references shouldn't be bound to the
definition within the shared library, or creating dynamically
linked executables to specify a list of symbols which should be
added to the symbol table in the executable. This option is only
meaningful on ELF platforms which support shared libraries.
The format of the dynamic list is the same as the version node
without scope and node name. See VERSION for more information.
--dynamic-list-data
Include all global data symbols to the dynamic list.
--dynamic-list-cpp-new
Provide the builtin dynamic list for C++ operator new and delete.
It is mainly useful for building shared libstdc++.
--dynamic-list-cpp-typeinfo
Provide the builtin dynamic list for C++ runtime type
identification.
--check-sections
--no-check-sections
Asks the linker not to check section addresses after they have been
assigned to see if there are any overlaps. Normally the linker
will perform this check, and if it finds any overlaps it will
produce suitable error messages. The linker does know about, and
does make allowances for sections in overlays. The default
behaviour can be restored by using the command-line switch
--check-sections. Section overlap is not usually checked for
relocatable links. You can force checking in that case by using
the --check-sections option.
--copy-dt-needed-entries
--no-copy-dt-needed-entries
This option affects the treatment of dynamic libraries referred to
by DT_NEEDED tags inside ELF dynamic libraries mentioned on the
command line. Normally the linker won't add a DT_NEEDED tag to the
output binary for each library mentioned in a DT_NEEDED tag in an
input dynamic library. With --copy-dt-needed-entries specified on
the command line however any dynamic libraries that follow it will
have their DT_NEEDED entries added. The default behaviour can be
restored with --no-copy-dt-needed-entries.
This option also has an effect on the resolution of symbols in
dynamic libraries. With --copy-dt-needed-entries dynamic libraries
mentioned on the command line will be recursively searched,
following their DT_NEEDED tags to other libraries, in order to
resolve symbols required by the output binary. With the default
setting however the searching of dynamic libraries that follow it
will stop with the dynamic library itself. No DT_NEEDED links will
be traversed to resolve symbols.
--cref
Output a cross reference table. If a linker map file is being
generated, the cross reference table is printed to the map file.
Otherwise, it is printed on the standard output.
The format of the table is intentionally simple, so that it may be
easily processed by a script if necessary. The symbols are printed
out, sorted by name. For each symbol, a list of file names is
given. If the symbol is defined, the first file listed is the
location of the definition. If the symbol is defined as a common
value then any files where this happens appear next. Finally any
files that reference the symbol are listed.
--ctf-variables
--no-ctf-variables
The CTF debuginfo format supports a section which encodes the names
and types of variables found in the program which do not appear in
any symbol table. These variables clearly cannot be looked up by
address by conventional debuggers, so the space used for their
types and names is usually wasted: the types are usually small but
the names are often not. --ctf-variables causes the generation of
such a section. The default behaviour can be restored with
--no-ctf-variables.
--ctf-share-types=method
Adjust the method used to share types between translation units in
CTF.
share-unconflicted
Put all types that do not have ambiguous definitions into the
shared dictionary, where debuggers can easily access them, even
if they only occur in one translation unit. This is the
default.
share-duplicated
Put only types that occur in multiple translation units into
the shared dictionary: types with only one definition go into
per-translation-unit dictionaries. Types with ambiguous
definitions in multiple translation units always go into
per-translation-unit dictionaries. This tends to make the CTF
larger, but may reduce the amount of CTF in the shared
dictionary. For very large projects this may speed up opening
the CTF and save memory in the CTF consumer at runtime.
--no-define-common
This option inhibits the assignment of addresses to common symbols.
The script command "INHIBIT_COMMON_ALLOCATION" has the same effect.
The --no-define-common option allows decoupling the decision to
assign addresses to Common symbols from the choice of the output
file type; otherwise a non-Relocatable output type forces assigning
addresses to Common symbols. Using --no-define-common allows
Common symbols that are referenced from a shared library to be
assigned addresses only in the main program. This eliminates the
unused duplicate space in the shared library, and also prevents any
possible confusion over resolving to the wrong duplicate when there
are many dynamic modules with specialized search paths for runtime
symbol resolution.
--force-group-allocation
This option causes the linker to place section group members like
normal input sections, and to delete the section groups. This is
the default behaviour for a final link but this option can be used
to change the behaviour of a relocatable link (-r). The script
command "FORCE_GROUP_ALLOCATION" has the same effect.
--defsym=symbol=expression
Create a global symbol in the output file, containing the absolute
address given by expression. You may use this option as many times
as necessary to define multiple symbols in the command line. A
limited form of arithmetic is supported for the expression in this
context: you may give a hexadecimal constant or the name of an
existing symbol, or use "+" and "-" to add or subtract hexadecimal
constants or symbols. If you need more elaborate expressions,
consider using the linker command language from a script. Note:
there should be no white space between symbol, the equals sign
("="), and expression.
The linker processes --defsym arguments and -T arguments in order,
placing --defsym before -T will define the symbol before the linker
script from -T is processed, while placing --defsym after -T will
define the symbol after the linker script has been processed. This
difference has consequences for expressions within the linker
script that use the --defsym symbols, which order is correct will
depend on what you are trying to achieve.
--demangle[=style]
--no-demangle
These options control whether to demangle symbol names in error
messages and other output. When the linker is told to demangle, it
tries to present symbol names in a readable fashion: it strips
leading underscores if they are used by the object file format, and
converts C++ mangled symbol names into user readable names.
Different compilers have different mangling styles. The optional
demangling style argument can be used to choose an appropriate
demangling style for your compiler. The linker will demangle by
default unless the environment variable COLLECT_NO_DEMANGLE is set.
These options may be used to override the default.
-Ifile
--dynamic-linker=file
Set the name of the dynamic linker. This is only meaningful when
generating dynamically linked ELF executables. The default dynamic
linker is normally correct; don't use this unless you know what you
are doing.
--no-dynamic-linker
When producing an executable file, omit the request for a dynamic
linker to be used at load-time. This is only meaningful for ELF
executables that contain dynamic relocations, and usually requires
entry point code that is capable of processing these relocations.
--embedded-relocs
This option is similar to the --emit-relocs option except that the
relocs are stored in a target-specific section. This option is
only supported by the BFIN, CR16 and M68K targets.
--disable-multiple-abs-defs
Do not allow multiple definitions with symbols included in filename
invoked by -R or --just-symbols
--fatal-warnings
--no-fatal-warnings
Treat all warnings as errors. The default behaviour can be
restored with the option --no-fatal-warnings.
-w
--no-warnings
Do not display any warning or error messages. This overrides
--fatal-warnings if it has been enabled. This option can be used
when it is known that the output binary will not work, but there is
still a need to create it.
--force-exe-suffix
Make sure that an output file has a .exe suffix.
If a successfully built fully linked output file does not have a
".exe" or ".dll" suffix, this option forces the linker to copy the
output file to one of the same name with a ".exe" suffix. This
option is useful when using unmodified Unix makefiles on a
Microsoft Windows host, since some versions of Windows won't run an
image unless it ends in a ".exe" suffix.
--gc-sections
--no-gc-sections
Enable garbage collection of unused input sections. It is ignored
on targets that do not support this option. The default behaviour
(of not performing this garbage collection) can be restored by
specifying --no-gc-sections on the command line. Note that garbage
collection for COFF and PE format targets is supported, but the
implementation is currently considered to be experimental.
--gc-sections decides which input sections are used by examining
symbols and relocations. The section containing the entry symbol
and all sections containing symbols undefined on the command-line
will be kept, as will sections containing symbols referenced by
dynamic objects. Note that when building shared libraries, the
linker must assume that any visible symbol is referenced. Once
this initial set of sections has been determined, the linker
recursively marks as used any section referenced by their
relocations. See --entry, --undefined, and --gc-keep-exported.
This option can be set when doing a partial link (enabled with
option -r). In this case the root of symbols kept must be
explicitly specified either by one of the options --entry,
--undefined, or --gc-keep-exported or by a "ENTRY" command in the
linker script.
As a GNU extension, ELF input sections marked with the
"SHF_GNU_RETAIN" flag will not be garbage collected.
--print-gc-sections
--no-print-gc-sections
List all sections removed by garbage collection. The listing is
printed on stderr. This option is only effective if garbage
collection has been enabled via the --gc-sections) option. The
default behaviour (of not listing the sections that are removed)
can be restored by specifying --no-print-gc-sections on the command
line.
--gc-keep-exported
When --gc-sections is enabled, this option prevents garbage
collection of unused input sections that contain global symbols
having default or protected visibility. This option is intended to
be used for executables where unreferenced sections would otherwise
be garbage collected regardless of the external visibility of
contained symbols. Note that this option has no effect when
linking shared objects since it is already the default behaviour.
This option is only supported for ELF format targets.
--print-output-format
Print the name of the default output format (perhaps influenced by
other command-line options). This is the string that would appear
in an "OUTPUT_FORMAT" linker script command.
--print-memory-usage
Print used size, total size and used size of memory regions created
with the MEMORY command. This is useful on embedded targets to
have a quick view of amount of free memory. The format of the
output has one headline and one line per region. It is both human
readable and easily parsable by tools. Here is an example of an
output:
Memory region Used Size Region Size %age Used
ROM: 256 KB 1 MB 25.00%
RAM: 32 B 2 GB 0.00%
--help
Print a summary of the command-line options on the standard output
and exit.
--target-help
Print a summary of all target-specific options on the standard
output and exit.
-Map=mapfile
Print a link map to the file mapfile. See the description of the
-M option, above. If mapfile is just the character "-" then the
map will be written to stdout.
Specifying a directory as mapfile causes the linker map to be
written as a file inside the directory. Normally name of the file
inside the directory is computed as the basename of the output file
with ".map" appended. If however the special character "%" is
used then this will be replaced by the full path of the output
file. Additionally if there are any characters after the % symbol
then ".map" will no longer be appended.
-o foo.exe -Map=bar [Creates ./bar]
-o ../dir/foo.exe -Map=bar [Creates ./bar]
-o foo.exe -Map=../dir [Creates ../dir/foo.exe.map]
-o ../dir2/foo.exe -Map=../dir [Creates ../dir/foo.exe.map]
-o foo.exe -Map=% [Creates ./foo.exe.map]
-o ../dir/foo.exe -Map=% [Creates ../dir/foo.exe.map]
-o foo.exe -Map=%.bar [Creates ./foo.exe.bar]
-o ../dir/foo.exe -Map=%.bar [Creates ../dir/foo.exe.bar]
-o ../dir2/foo.exe -Map=../dir/% [Creates ../dir/../dir2/foo.exe.map]
-o ../dir2/foo.exe -Map=../dir/%.bar [Creates ../dir/../dir2/foo.exe.bar]
It is an error to specify more than one "%" character.
If the map file already exists then it will be overwritten by this
operation.
--no-keep-memory
ld normally optimizes for speed over memory usage by caching the
symbol tables of input files in memory. This option tells ld to
instead optimize for memory usage, by rereading the symbol tables
as necessary. This may be required if ld runs out of memory space
while linking a large executable.
--no-undefined
-z defs
Report unresolved symbol references from regular object files.
This is done even if the linker is creating a non-symbolic shared
library. The switch --[no-]allow-shlib-undefined controls the
behaviour for reporting unresolved references found in shared
libraries being linked in.
The effects of this option can be reverted by using "-z undefs".
--allow-multiple-definition
-z muldefs
Normally when a symbol is defined multiple times, the linker will
report a fatal error. These options allow multiple definitions and
the first definition will be used.
--allow-shlib-undefined
--no-allow-shlib-undefined
Allows or disallows undefined symbols in shared libraries. This
switch is similar to --no-undefined except that it determines the
behaviour when the undefined symbols are in a shared library rather
than a regular object file. It does not affect how undefined
symbols in regular object files are handled.
The default behaviour is to report errors for any undefined symbols
referenced in shared libraries if the linker is being used to
create an executable, but to allow them if the linker is being used
to create a shared library.
The reasons for allowing undefined symbol references in shared
libraries specified at link time are that:
• A shared library specified at link time may not be the same as
the one that is available at load time, so the symbol might
actually be resolvable at load time.
• There are some operating systems, eg BeOS and HPPA, where
undefined symbols in shared libraries are normal.
The BeOS kernel for example patches shared libraries at load
time to select whichever function is most appropriate for the
current architecture. This is used, for example, to
dynamically select an appropriate memset function.
--error-handling-script=scriptname
If this option is provided then the linker will invoke scriptname
whenever an error is encountered. Currently however only two kinds
of error are supported: missing symbols and missing libraries. Two
arguments will be passed to script: the keyword "undefined-symbol"
or `missing-lib" and the name of the undefined symbol or missing
library. The intention is that the script will provide suggestions
to the user as to where the symbol or library might be found.
After the script has finished then the normal linker error message
will be displayed.
The availability of this option is controlled by a configure time
switch, so it may not be present in specific implementations.
--no-undefined-version
Normally when a symbol has an undefined version, the linker will
ignore it. This option disallows symbols with undefined version and
a fatal error will be issued instead.
--default-symver
Create and use a default symbol version (the soname) for
unversioned exported symbols.
--default-imported-symver
Create and use a default symbol version (the soname) for
unversioned imported symbols.
--no-warn-mismatch
Normally ld will give an error if you try to link together input
files that are mismatched for some reason, perhaps because they
have been compiled for different processors or for different
endiannesses. This option tells ld that it should silently permit
such possible errors. This option should only be used with care,
in cases when you have taken some special action that ensures that
the linker errors are inappropriate.
--no-warn-search-mismatch
Normally ld will give a warning if it finds an incompatible library
during a library search. This option silences the warning.
--no-whole-archive
Turn off the effect of the --whole-archive option for subsequent
archive files.
--noinhibit-exec
Retain the executable output file whenever it is still usable.
Normally, the linker will not produce an output file if it
encounters errors during the link process; it exits without writing
an output file when it issues any error whatsoever.
-nostdlib
Only search library directories explicitly specified on the command
line. Library directories specified in linker scripts (including
linker scripts specified on the command line) are ignored.
--oformat=output-format
ld may be configured to support more than one kind of object file.
If your ld is configured this way, you can use the --oformat option
to specify the binary format for the output object file. Even when
ld is configured to support alternative object formats, you don't
usually need to specify this, as ld should be configured to produce
as a default output format the most usual format on each machine.
output-format is a text string, the name of a particular format
supported by the BFD libraries. (You can list the available binary
formats with objdump -i.) The script command "OUTPUT_FORMAT" can
also specify the output format, but this option overrides it.
--out-implib file
Create an import library in file corresponding to the executable
the linker is generating (eg. a DLL or ELF program). This import
library (which should be called "*.dll.a" or "*.a" for DLLs) may be
used to link clients against the generated executable; this
behaviour makes it possible to skip a separate import library
creation step (eg. "dlltool" for DLLs). This option is only
available for the i386 PE and ELF targetted ports of the linker.
-pie
--pic-executable
Create a position independent executable. This is currently only
supported on ELF platforms. Position independent executables are
relocated by the dynamic linker to the virtual address the OS
chooses for them, which can vary between invocations. They are
marked ET_DYN in the ELF file header, but differ from shared
libraries in a number of ways. In particular, defined symbols in a
PIE by default can not be overridden by another object as they can
be in a shared library.
-no-pie
Create a position dependent executable. This is the default.
-qmagic
This option is ignored for Linux compatibility.
-Qy This option is ignored for SVR4 compatibility.
--relax
--no-relax
An option with machine dependent effects. This option is only
supported on a few targets.
On some platforms the --relax option performs target specific,
global optimizations that become possible when the linker resolves
addressing in the program, such as relaxing address modes,
synthesizing new instructions, selecting shorter version of current
instructions, and combining constant values.
On some platforms these link time global optimizations may make
symbolic debugging of the resulting executable impossible. This is
known to be the case for the Matsushita MN10200 and MN10300 family
of processors.
On platforms where the feature is supported, the option --no-relax
will disable it.
On platforms where the feature is not supported, both --relax and
--no-relax are accepted, but ignored.
--retain-symbols-file=filename
Retain only the symbols listed in the file filename, discarding all
others. filename is simply a flat file, with one symbol name per
line. This option is especially useful in environments (such as
VxWorks) where a large global symbol table is accumulated
gradually, to conserve run-time memory.
--retain-symbols-file does not discard undefined symbols, or
symbols needed for relocations.
You may only specify --retain-symbols-file once in the command
line. It overrides -s and -S.
-rpath=dir
Add a directory to the runtime library search path. This is used
when linking an ELF executable with shared objects. All -rpath
arguments are concatenated and passed to the runtime linker, which
uses them to locate shared objects at runtime.
The -rpath option is also used when locating shared objects which
are needed by shared objects explicitly included in the link; see
the description of the -rpath-link option. Searching -rpath in
this way is only supported by native linkers and cross linkers
which have been configured with the --with-sysroot option.
If -rpath is not used when linking an ELF executable, the contents
of the environment variable "LD_RUN_PATH" will be used if it is
defined.
The -rpath option may also be used on SunOS. By default, on SunOS,
the linker will form a runtime search path out of all the -L
options it is given. If a -rpath option is used, the runtime
search path will be formed exclusively using the -rpath options,
ignoring the -L options. This can be useful when using gcc, which
adds many -L options which may be on NFS mounted file systems.
For compatibility with other ELF linkers, if the -R option is
followed by a directory name, rather than a file name, it is
treated as the -rpath option.
-rpath-link=dir
When using ELF or SunOS, one shared library may require another.
This happens when an "ld -shared" link includes a shared library as
one of the input files.
When the linker encounters such a dependency when doing a
non-shared, non-relocatable link, it will automatically try to
locate the required shared library and include it in the link, if
it is not included explicitly. In such a case, several directories
are searched as described below. The -rpath-link option specifies
the first set of directories to search. This option may specify a
sequence of directory names either by providing a list of names
separated by colons, or by appearing multiple times.
The tokens $ORIGIN and $LIB can appear in these search directories.
They will be replaced by the full path to the directory containing
the program or shared object in the case of $ORIGIN and either lib
- for 32-bit binaries - or lib64 - for 64-bit binaries - in the
case of $LIB.
The alternative form of these tokens - ${ORIGIN} and ${LIB} can
also be used. The token $PLATFORM is not supported.
The --rpath-link option should be used with caution as it overrides
the search path that may have been hard compiled into a shared
library. In such a case it is possible to unintentionally use a
different search path than the runtime linker would have used.
When additional shared libraries are required, the linker will
search directories in the order listed below in order to find them.
Note however that this only applies to additional libraries needed
to satisfy already included shared libraries. It does not apply to
libraries that are included via the -l command line option.
Searches for -l libraries are only conducted in directories
specified by the -L option.
1. Any directories specified by -rpath-link options.
2. Any directories specified by -rpath options. The difference
between -rpath and -rpath-link is that directories specified by
-rpath options are included in the executable and used at
runtime, whereas the -rpath-link option is only effective at
link time. Searching -rpath in this way is only supported by
native linkers and cross linkers which have been configured
with the --with-sysroot option.
3. On an ELF system, for native linkers, if the -rpath and
-rpath-link options were not used, search the contents of the
environment variable "LD_RUN_PATH".
4. On SunOS, if the -rpath option was not used, search any
directories specified using -L options.
5. For a native linker, search the contents of the environment
variable "LD_LIBRARY_PATH".
6. For a native ELF linker, the directories in "DT_RUNPATH" or
"DT_RPATH" of a shared library are searched for shared
libraries needed by it. The "DT_RPATH" entries are ignored if
"DT_RUNPATH" entries exist.
7. For a linker for a Linux system, if the file /etc/ld.so.conf
exists, the list of directories found in that file. Note: the
path to this file is prefixed with the "sysroot" value, if that
is defined, and then any "prefix" string if the linker was
configured with the --prefix=<path> option.
8. For a native linker on a FreeBSD system, any directories
specified by the "_PATH_ELF_HINTS" macro defined in the
elf-hints.h header file.
9. Any directories specified by a "SEARCH_DIR" command in a linker
script given on the command line, including scripts specified
by -T (but not -dT).
10. The default directories, normally /lib and /usr/lib.
11. Any directories specified by a plugin
LDPT_SET_EXTRA_LIBRARY_PATH.
12. Any directories specified by a "SEARCH_DIR" command in a
default linker script.
Note however on Linux based systems there is an additional caveat:
If the --as-needed option is active and a shared library is located
which would normally satisfy the search and this library does not
have DT_NEEDED tag for libc.so and there is a shared library later
on in the set of search directories which also satisfies the search
and this second shared library does have a DT_NEEDED tag for
libc.so then the second library will be selected instead of the
first.
If the required shared library is not found, the linker will issue
a warning and continue with the link.
--section-ordering-file=script
This option is used to augment the current linker script with
additional mapping of input sections to output sections. This file
must use the same syntax for "SECTIONS" as is used in normal linker
scripts, but it should not do anything other than place input
sections into output sections. @pxref{SECTIONS}
A second constraint on the section ordering script is that it can
only reference output sections that are already defined by
whichever linker script is currently in use. (Ie the default
linker script or a script specified on the command line). The
benefit of the section ordering script however is that the input
sections are mapped to the start of the output sections, so that
they can ensure the ordering of sections in the output section.
For example, imagine that the default linker script looks like
this:
SECTIONS {
.text : { *(.text.hot) ; *(.text .text.*) }
.data : { *(.data.big) ; *(.data .data.*) }
}
Then if a section ordering file like this is used:
.text : { *(.text.first) ; *(.text.z*) }
.data : { foo.o(.data.first) ; *(.data.small) }
This would be equivalent to a linker script like this:
SECTIONS {
.text : { *(.text.first) ; *(.text.z*) ; *(.text.hot) ; *(.text .text.*) }
.data : { foo.o(.data.first) ; *(.data.small) ; *(.data.big) ; *(.data .data.*) }
}
The advantage of the section ordering file is that it can be used
to order those sections that matter to the user without having to
worry about any other sections, or memory regions, or anything
else.
-shared
-Bshareable
Create a shared library. This is currently only supported on ELF,
XCOFF and SunOS platforms. On SunOS, the linker will automatically
create a shared library if the -e option is not used and there are
undefined symbols in the link.
--sort-common
--sort-common=ascending
--sort-common=descending
This option tells ld to sort the common symbols by alignment in
ascending or descending order when it places them in the
appropriate output sections. The symbol alignments considered are
sixteen-byte or larger, eight-byte, four-byte, two-byte, and
one-byte. This is to prevent gaps between symbols due to alignment
constraints. If no sorting order is specified, then descending
order is assumed.
--sort-section=name
This option will apply "SORT_BY_NAME" to all wildcard section
patterns in the linker script.
--sort-section=alignment
This option will apply "SORT_BY_ALIGNMENT" to all wildcard section
patterns in the linker script.
--spare-dynamic-tags=count
This option specifies the number of empty slots to leave in the
.dynamic section of ELF shared objects. Empty slots may be needed
by post processing tools, such as the prelinker. The default is 5.
--split-by-file[=size]
Similar to --split-by-reloc but creates a new output section for
each input file when size is reached. size defaults to a size of 1
if not given.
--split-by-reloc[=count]
Tries to creates extra sections in the output file so that no
single output section in the file contains more than count
relocations. This is useful when generating huge relocatable files
for downloading into certain real time kernels with the COFF object
file format; since COFF cannot represent more than 65535
relocations in a single section. Note that this will fail to work
with object file formats which do not support arbitrary sections.
The linker will not split up individual input sections for
redistribution, so if a single input section contains more than
count relocations one output section will contain that many
relocations. count defaults to a value of 32768.
--stats
Compute and display statistics about the operation of the linker,
such as execution time and memory usage.
--sysroot=directory
Use directory as the location of the sysroot, overriding the
configure-time default. This option is only supported by linkers
that were configured using --with-sysroot.
--task-link
This is used by COFF/PE based targets to create a task-linked
object file where all of the global symbols have been converted to
statics.
--traditional-format
For some targets, the output of ld is different in some ways from
the output of some existing linker. This switch requests ld to use
the traditional format instead.
For example, on SunOS, ld combines duplicate entries in the symbol
string table. This can reduce the size of an output file with full
debugging information by over 30 percent. Unfortunately, the SunOS
"dbx" program can not read the resulting program ("gdb" has no
trouble). The --traditional-format switch tells ld to not combine
duplicate entries.
--section-start=sectionname=org
Locate a section in the output file at the absolute address given
by org. You may use this option as many times as necessary to
locate multiple sections in the command line. org must be a single
hexadecimal integer; for compatibility with other linkers, you may
omit the leading 0x usually associated with hexadecimal values.
Note: there should be no white space between sectionname, the
equals sign ("="), and org.
--image-base=org
When using ELF, same as -Ttext-segment, with both options
effectively setting the base address of the ELF executable.
When using PE, use value as the base address of your program or
dll. This is the lowest memory location that will be used when
your program or dll is loaded. To reduce the need to relocate and
improve performance of your dlls, each should have a unique base
address and not overlap any other dlls. The default is 0x400000
for executables, and 0x10000000 for dlls.
-Tbss=org
-Tdata=org
-Ttext=org
Same as --section-start, with ".bss", ".data" or ".text" as the
sectionname.
-Ttext-segment=org
When creating an ELF executable, it will set the address of the
first byte of the first segment. Note that when -pie is used with
-Ttext-segment=org, the output executable is marked ET_EXEC so that
the address of the first byte of the text segment will be
guaranteed to be org at run time.
-Trodata-segment=org
When creating an ELF executable or shared object for a target where
the read-only data is in its own segment separate from the
executable text, it will set the address of the first byte of the
read-only data segment.
-Tldata-segment=org
When creating an ELF executable or shared object for x86-64 medium
memory model, it will set the address of the first byte of the
ldata segment.
--unresolved-symbols=method
Determine how to handle unresolved symbols. There are four
possible values for method:
ignore-all
Do not report any unresolved symbols.
report-all
Report all unresolved symbols. This is the default.
ignore-in-object-files
Report unresolved symbols that are contained in shared
libraries, but ignore them if they come from regular object
files.
ignore-in-shared-libs
Report unresolved symbols that come from regular object files,
but ignore them if they come from shared libraries. This can
be useful when creating a dynamic binary and it is known that
all the shared libraries that it should be referencing are
included on the linker's command line.
The behaviour for shared libraries on their own can also be
controlled by the --[no-]allow-shlib-undefined option.
Normally the linker will generate an error message for each
reported unresolved symbol but the option --warn-unresolved-symbols
can change this to a warning.
--dll-verbose
--verbose[=NUMBER]
Display the version number for ld and list the linker emulations
supported. Display which input files can and cannot be opened.
Display the linker script being used by the linker. If the optional
NUMBER argument > 1, plugin symbol status will also be displayed.
--version-script=version-scriptfile
Specify the name of a version script to the linker. This is
typically used when creating shared libraries to specify additional
information about the version hierarchy for the library being
created. This option is only fully supported on ELF platforms
which support shared libraries; see VERSION. It is partially
supported on PE platforms, which can use version scripts to filter
symbol visibility in auto-export mode: any symbols marked local in
the version script will not be exported.
--warn-common
Warn when a common symbol is combined with another common symbol or
with a symbol definition. Unix linkers allow this somewhat sloppy
practice, but linkers on some other operating systems do not. This
option allows you to find potential problems from combining global
symbols. Unfortunately, some C libraries use this practice, so you
may get some warnings about symbols in the libraries as well as in
your programs.
There are three kinds of global symbols, illustrated here by C
examples:
int i = 1;
A definition, which goes in the initialized data section of the
output file.
extern int i;
An undefined reference, which does not allocate space. There
must be either a definition or a common symbol for the variable
somewhere.
int i;
A common symbol. If there are only (one or more) common
symbols for a variable, it goes in the uninitialized data area
of the output file. The linker merges multiple common symbols
for the same variable into a single symbol. If they are of
different sizes, it picks the largest size. The linker turns a
common symbol into a declaration, if there is a definition of
the same variable.
The --warn-common option can produce five kinds of warnings. Each
warning consists of a pair of lines: the first describes the symbol
just encountered, and the second describes the previous symbol
encountered with the same name. One or both of the two symbols
will be a common symbol.
1. Turning a common symbol into a reference, because there is
already a definition for the symbol.
<file>(<section>): warning: common of `<symbol>'
overridden by definition
<file>(<section>): warning: defined here
2. Turning a common symbol into a reference, because a later
definition for the symbol is encountered. This is the same as
the previous case, except that the symbols are encountered in a
different order.
<file>(<section>): warning: definition of `<symbol>'
overriding common
<file>(<section>): warning: common is here
3. Merging a common symbol with a previous same-sized common
symbol.
<file>(<section>): warning: multiple common
of `<symbol>'
<file>(<section>): warning: previous common is here
4. Merging a common symbol with a previous larger common symbol.
<file>(<section>): warning: common of `<symbol>'
overridden by larger common
<file>(<section>): warning: larger common is here
5. Merging a common symbol with a previous smaller common symbol.
This is the same as the previous case, except that the symbols
are encountered in a different order.
<file>(<section>): warning: common of `<symbol>'
overriding smaller common
<file>(<section>): warning: smaller common is here
--warn-constructors
Warn if any global constructors are used. This is only useful for
a few object file formats. For formats like COFF or ELF, the
linker can not detect the use of global constructors.
--warn-execstack
--warn-execstack-objects
--no-warn-execstack
On ELF platforms the linker may generate warning messages if it is
asked to create an output file that contains an executable stack.
There are three possible states:
1. Do not generate any warnings.
2. Always generate warnings, even if the executable stack is
requested via the -z execstack command line option.
3. Only generate a warning if an object file requests an
executable stack, but not if the -z execstack option is used.
The default state depends upon how the linker was configured when
it was built. The --no-warn-execstack option always puts the
linker into the no-warnings state. The --warn-execstack option
puts the linker into the warn-always state. The
--warn-execstack-objects option puts the linker into the
warn-for-object-files-only state.
Note: ELF format input files can specify that they need an
executable stack by having a .note.GNU-stack section with the
executable bit set in its section flags. They can specify that
they do not need an executable stack by having the same section,
but without the executable flag bit set. If an input file does not
have a .note.GNU-stack section then the default behaviour is target
specific. For some targets, then absence of such a section implies
that an executable stack is required. This is often a problem for
hand crafted assembler files.
--error-execstack
--no-error-execstack
If the linker is going to generate a warning message about an
executable stack then the --error-execstack option will instead
change that warning into an error. Note - this option does not
change the linker's execstack warning generation state. Use
--warn-execstack or --warn-execstack-objects to set a specific
warning state.
The --no-error-execstack option will restore the default behaviour
of generating warning messages.
--warn-multiple-gp
Warn if multiple global pointer values are required in the output
file. This is only meaningful for certain processors, such as the
Alpha. Specifically, some processors put large-valued constants in
a special section. A special register (the global pointer) points
into the middle of this section, so that constants can be loaded
efficiently via a base-register relative addressing mode. Since
the offset in base-register relative mode is fixed and relatively
small (e.g., 16 bits), this limits the maximum size of the constant
pool. Thus, in large programs, it is often necessary to use
multiple global pointer values in order to be able to address all
possible constants. This option causes a warning to be issued
whenever this case occurs.
--warn-once
Only warn once for each undefined symbol, rather than once per
module which refers to it.
--warn-rwx-segments
--no-warn-rwx-segments
Warn if the linker creates a loadable, non-zero sized segment that
has all three of the read, write and execute permission flags set.
Such a segment represents a potential security vulnerability. In
addition warnings will be generated if a thread local storage
segment is created with the execute permission flag set, regardless
of whether or not it has the read and/or write flags set.
These warnings are enabled by default. They can be disabled via
the --no-warn-rwx-segments option and re-enabled via the
--warn-rwx-segments option.
--error-rwx-segments
--no-error-rwx-segments
If the linker is going to generate a warning message about an
executable, writeable segment, or an executable TLS segment, then
the --error-rwx-segments option will turn this warning into an
error instead. The --no-error-rwx-segments option will restore the
default behaviour of just generating a warning message.
Note - the --error-rwx-segments option does not by itself turn on
warnings about these segments. These warnings are either enabled
by default, if the linker was configured that way, or via the
--warn-rwx-segments command line option.
--warn-section-align
Warn if the address of an output section is changed because of
alignment. Typically, the alignment will be set by an input
section. The address will only be changed if it not explicitly
specified; that is, if the "SECTIONS" command does not specify a
start address for the section.
--warn-textrel
Warn if the linker adds DT_TEXTREL to a position-independent
executable or shared object.
--warn-alternate-em
Warn if an object has alternate ELF machine code.
--warn-unresolved-symbols
If the linker is going to report an unresolved symbol (see the
option --unresolved-symbols) it will normally generate an error.
This option makes it generate a warning instead.
--error-unresolved-symbols
This restores the linker's default behaviour of generating errors
when it is reporting unresolved symbols.
--whole-archive
For each archive mentioned on the command line after the
--whole-archive option, include every object file in the archive in
the link, rather than searching the archive for the required object
files. This is normally used to turn an archive file into a shared
library, forcing every object to be included in the resulting
shared library. This option may be used more than once.
Two notes when using this option from gcc: First, gcc doesn't know
about this option, so you have to use -Wl,-whole-archive. Second,
don't forget to use -Wl,-no-whole-archive after your list of
archives, because gcc will add its own list of archives to your
link and you may not want this flag to affect those as well.
--wrap=symbol
Use a wrapper function for symbol. Any undefined reference to
symbol will be resolved to "__wrap_symbol". Any undefined
reference to "__real_symbol" will be resolved to symbol.
This can be used to provide a wrapper for a system function. The
wrapper function should be called "__wrap_symbol". If it wishes to
call the system function, it should call "__real_symbol".
Here is a trivial example:
void *
__wrap_malloc (size_t c)
{
printf ("malloc called with %zu\n", c);
return __real_malloc (c);
}
If you link other code with this file using --wrap malloc, then all
calls to "malloc" will call the function "__wrap_malloc" instead.
The call to "__real_malloc" in "__wrap_malloc" will call the real
"malloc" function.
You may wish to provide a "__real_malloc" function as well, so that
links without the --wrap option will succeed. If you do this, you
should not put the definition of "__real_malloc" in the same file
as "__wrap_malloc"; if you do, the assembler may resolve the call
before the linker has a chance to wrap it to "malloc".
Only undefined references are replaced by the linker. So,
translation unit internal references to symbol are not resolved to
"__wrap_symbol". In the next example, the call to "f" in "g" is
not resolved to "__wrap_f".
int
f (void)
{
return 123;
}
int
g (void)
{
return f();
}
--eh-frame-hdr
--no-eh-frame-hdr
Request (--eh-frame-hdr) or suppress (--no-eh-frame-hdr) the
creation of ".eh_frame_hdr" section and ELF "PT_GNU_EH_FRAME"
segment header.
--no-ld-generated-unwind-info
Request creation of ".eh_frame" unwind info for linker generated
code sections like PLT. This option is on by default if linker
generated unwind info is supported. This option also controls the
generation of ".sframe" stack trace info for linker generated code
sections like PLT.
--enable-new-dtags
--disable-new-dtags
This linker can create the new dynamic tags in ELF. But the older
ELF systems may not understand them. If you specify
--enable-new-dtags, the new dynamic tags will be created as needed
and older dynamic tags will be omitted. If you specify
--disable-new-dtags, no new dynamic tags will be created. By
default, the new dynamic tags are not created. Note that those
options are only available for ELF systems.
--hash-size=number
Set the default size of the linker's hash tables to a prime number
close to number. Increasing this value can reduce the length of
time it takes the linker to perform its tasks, at the expense of
increasing the linker's memory requirements. Similarly reducing
this value can reduce the memory requirements at the expense of
speed.
--hash-style=style
Set the type of linker's hash table(s). style can be either "sysv"
for classic ELF ".hash" section, "gnu" for new style GNU
".gnu.hash" section or "both" for both the classic ELF ".hash" and
new style GNU ".gnu.hash" hash tables. The default depends upon
how the linker was configured, but for most Linux based systems it
will be "both".
--compress-debug-sections=none
--compress-debug-sections=zlib
--compress-debug-sections=zlib-gnu
--compress-debug-sections=zlib-gabi
--compress-debug-sections=zstd
On ELF platforms, these options control how DWARF debug sections
are compressed using zlib.
--compress-debug-sections=none doesn't compress DWARF debug
sections. --compress-debug-sections=zlib-gnu compresses DWARF
debug sections and renames them to begin with .zdebug instead of
.debug. --compress-debug-sections=zlib-gabi also compresses DWARF
debug sections, but rather than renaming them it sets the
SHF_COMPRESSED flag in the sections' headers.
The --compress-debug-sections=zlib option is an alias for
--compress-debug-sections=zlib-gabi.
--compress-debug-sections=zstd compresses DWARF debug sections
using zstd.
Note that this option overrides any compression in input debug
sections, so if a binary is linked with
--compress-debug-sections=none for example, then any compressed
debug sections in input files will be uncompressed before they are
copied into the output binary.
The default compression behaviour varies depending upon the target
involved and the configure options used to build the toolchain.
The default can be determined by examining the output from the
linker's --help option.
--reduce-memory-overheads
This option reduces memory requirements at ld runtime, at the
expense of linking speed. This was introduced to select the old
O(n^2) algorithm for link map file generation, rather than the new
O(n) algorithm which uses about 40% more memory for symbol storage.
Another effect of the switch is to set the default hash table size
to 1021, which again saves memory at the cost of lengthening the
linker's run time. This is not done however if the --hash-size
switch has been used.
The --reduce-memory-overheads switch may be also be used to enable
other tradeoffs in future versions of the linker.
--max-cache-size=size
ld normally caches the relocation information and symbol tables of
input files in memory with the unlimited size. This option sets
the maximum cache size to size.
--build-id
--build-id=style
Request the creation of a ".note.gnu.build-id" ELF note section or
a ".buildid" COFF section. The contents of the note are unique
bits identifying this linked file. style can be "uuid" to use 128
random bits; "sha1" to use a 160-bit SHA1 hash, "md5" to use a
128-bit MD5 hash, or "xx" to use a 128-bit XXHASH on the normative
parts of the output contents; or "0xhexstring" to use a chosen bit
string specified as an even number of hexadecimal digits ("-" and
":" characters between digit pairs are ignored). If style is
omitted, "sha1" is used.
The "md5", "sha1", and "xx" styles produces an identifier that is
always the same in an identical output file, but are almost
certainly unique among all nonidentical output files. It is not
intended to be compared as a checksum for the file's contents. A
linked file may be changed later by other tools, but the build ID
bit string identifying the original linked file does not change.
Passing "none" for style disables the setting from any "--build-id"
options earlier on the command line.
--package-metadata=JSON
Request the creation of a ".note.package" ELF note section. The
contents of the note are in JSON format, as per the package
metadata specification. For more information see:
https://systemd.io/ELF_PACKAGE_METADATA/ The JSON argument support
percent-encoding and following %[string] (where string refers to
the name in HTML's Named Character References) encoding: %[comma]
for ,, %[lbrace] for {, %[quot] for ", %[rbrace] for }, and
%[space] for space character. If the JSON argument is
missing/empty then this will disable the creation of the metadata
note, if one had been enabled by an earlier occurrence of the
--package-metadata option. If the linker has been built with
libjansson, then the JSON string will be validated.
The i386 PE linker supports the -shared option, which causes the output
to be a dynamically linked library (DLL) instead of a normal
executable. You should name the output "*.dll" when you use this
option. In addition, the linker fully supports the standard "*.def"
files, which may be specified on the linker command line like an object
file (in fact, it should precede archives it exports symbols from, to
ensure that they get linked in, just like a normal object file).
In addition to the options common to all targets, the i386 PE linker
support additional command-line options that are specific to the i386
PE target. Options that take values may be separated from their values
by either a space or an equals sign.
--add-stdcall-alias
If given, symbols with a stdcall suffix (@nn) will be exported
as-is and also with the suffix stripped. [This option is specific
to the i386 PE targeted port of the linker]
--base-file file
Use file as the name of a file in which to save the base addresses
of all the relocations needed for generating DLLs with dlltool.
[This is an i386 PE specific option]
--dll
Create a DLL instead of a regular executable. You may also use
-shared or specify a "LIBRARY" in a given ".def" file. [This
option is specific to the i386 PE targeted port of the linker]
--enable-long-section-names
--disable-long-section-names
The PE variants of the COFF object format add an extension that
permits the use of section names longer than eight characters, the
normal limit for COFF. By default, these names are only allowed in
object files, as fully-linked executable images do not carry the
COFF string table required to support the longer names. As a GNU
extension, it is possible to allow their use in executable images
as well, or to (probably pointlessly!) disallow it in object
files, by using these two options. Executable images generated
with these long section names are slightly non-standard, carrying
as they do a string table, and may generate confusing output when
examined with non-GNU PE-aware tools, such as file viewers and
dumpers. However, GDB relies on the use of PE long section names
to find Dwarf-2 debug information sections in an executable image
at runtime, and so if neither option is specified on the
command-line, ld will enable long section names, overriding the
default and technically correct behaviour, when it finds the
presence of debug information while linking an executable image and
not stripping symbols. [This option is valid for all PE targeted
ports of the linker]
--enable-stdcall-fixup
--disable-stdcall-fixup
If the link finds a symbol that it cannot resolve, it will attempt
to do "fuzzy linking" by looking for another defined symbol that
differs only in the format of the symbol name (cdecl vs stdcall)
and will resolve that symbol by linking to the match. For example,
the undefined symbol "_foo" might be linked to the function
"_foo@12", or the undefined symbol "_bar@16" might be linked to the
function "_bar". When the linker does this, it prints a warning,
since it normally should have failed to link, but sometimes import
libraries generated from third-party dlls may need this feature to
be usable. If you specify --enable-stdcall-fixup, this feature is
fully enabled and warnings are not printed. If you specify
--disable-stdcall-fixup, this feature is disabled and such
mismatches are considered to be errors. [This option is specific
to the i386 PE targeted port of the linker]
--leading-underscore
--no-leading-underscore
For most targets default symbol-prefix is an underscore and is
defined in target's description. By this option it is possible to
disable/enable the default underscore symbol-prefix.
--export-all-symbols
If given, all global symbols in the objects used to build a DLL
will be exported by the DLL. Note that this is the default if
there otherwise wouldn't be any exported symbols. When symbols are
explicitly exported via DEF files or implicitly exported via
function attributes, the default is to not export anything else
unless this option is given. Note that the symbols "DllMain@12",
"DllEntryPoint@0", "DllMainCRTStartup@12", and "impure_ptr" will
not be automatically exported. Also, symbols imported from other
DLLs will not be re-exported, nor will symbols specifying the DLL's
internal layout such as those beginning with "_head_" or ending
with "_iname". In addition, no symbols from "libgcc", "libstd++",
"libmingw32", or "crtX.o" will be exported. Symbols whose names
begin with "__rtti_" or "__builtin_" will not be exported, to help
with C++ DLLs. Finally, there is an extensive list of
cygwin-private symbols that are not exported (obviously, this
applies on when building DLLs for cygwin targets). These
cygwin-excludes are: "_cygwin_dll_entry@12",
"_cygwin_crt0_common@8", "_cygwin_noncygwin_dll_entry@12",
"_fmode", "_impure_ptr", "cygwin_attach_dll", "cygwin_premain0",
"cygwin_premain1", "cygwin_premain2", "cygwin_premain3", and
"environ". [This option is specific to the i386 PE targeted port
of the linker]
--exclude-symbols symbol,symbol,...
Specifies a list of symbols which should not be automatically
exported. The symbol names may be delimited by commas or colons.
[This option is specific to the i386 PE targeted port of the
linker]
--exclude-all-symbols
Specifies no symbols should be automatically exported. [This
option is specific to the i386 PE targeted port of the linker]
--file-alignment
Specify the file alignment. Sections in the file will always begin
at file offsets which are multiples of this number. This defaults
to 512. [This option is specific to the i386 PE targeted port of
the linker]
--heap reserve
--heap reserve,commit
Specify the number of bytes of memory to reserve (and optionally
commit) to be used as heap for this program. The default is 1MB
reserved, 4K committed. [This option is specific to the i386 PE
targeted port of the linker]
--kill-at
If given, the stdcall suffixes (@nn) will be stripped from symbols
before they are exported. [This option is specific to the i386 PE
targeted port of the linker]
--large-address-aware
If given, the appropriate bit in the "Characteristics" field of the
COFF header is set to indicate that this executable supports
virtual addresses greater than 2 gigabytes. This should be used in
conjunction with the /3GB or /USERVA=value megabytes switch in the
"[operating systems]" section of the BOOT.INI. Otherwise, this bit
has no effect. [This option is specific to PE targeted ports of
the linker]
--disable-large-address-aware
Reverts the effect of a previous --large-address-aware option.
This is useful if --large-address-aware is always set by the
compiler driver (e.g. Cygwin gcc) and the executable does not
support virtual addresses greater than 2 gigabytes. [This option
is specific to PE targeted ports of the linker]
--major-image-version value
Sets the major number of the "image version". Defaults to 1.
[This option is specific to the i386 PE targeted port of the
linker]
--major-os-version value
Sets the major number of the "os version". Defaults to 4. [This
option is specific to the i386 PE targeted port of the linker]
--major-subsystem-version value
Sets the major number of the "subsystem version". Defaults to 4.
[This option is specific to the i386 PE targeted port of the
linker]
--minor-image-version value
Sets the minor number of the "image version". Defaults to 0.
[This option is specific to the i386 PE targeted port of the
linker]
--minor-os-version value
Sets the minor number of the "os version". Defaults to 0. [This
option is specific to the i386 PE targeted port of the linker]
--minor-subsystem-version value
Sets the minor number of the "subsystem version". Defaults to 0.
[This option is specific to the i386 PE targeted port of the
linker]
--output-def file
The linker will create the file file which will contain a DEF file
corresponding to the DLL the linker is generating. This DEF file
(which should be called "*.def") may be used to create an import
library with "dlltool" or may be used as a reference to
automatically or implicitly exported symbols. [This option is
specific to the i386 PE targeted port of the linker]
--enable-auto-image-base
--enable-auto-image-base=value
Automatically choose the image base for DLLs, optionally starting
with base value, unless one is specified using the "--image-base"
argument. By using a hash generated from the dllname to create
unique image bases for each DLL, in-memory collisions and
relocations which can delay program execution are avoided. [This
option is specific to the i386 PE targeted port of the linker]
--disable-auto-image-base
Do not automatically generate a unique image base. If there is no
user-specified image base ("--image-base") then use the platform
default. [This option is specific to the i386 PE targeted port of
the linker]
--dll-search-prefix string
When linking dynamically to a dll without an import library, search
for "<string><basename>.dll" in preference to "lib<basename>.dll".
This behaviour allows easy distinction between DLLs built for the
various "subplatforms": native, cygwin, uwin, pw, etc. For
instance, cygwin DLLs typically use "--dll-search-prefix=cyg".
[This option is specific to the i386 PE targeted port of the
linker]
--enable-auto-import
Do sophisticated linking of "_symbol" to "__imp__symbol" for DATA
imports from DLLs, thus making it possible to bypass the dllimport
mechanism on the user side and to reference unmangled symbol names.
[This option is specific to the i386 PE targeted port of the
linker]
The following remarks pertain to the original implementation of the
feature and are obsolete nowadays for Cygwin and MinGW targets.
Note: Use of the 'auto-import' extension will cause the text
section of the image file to be made writable. This does not
conform to the PE-COFF format specification published by Microsoft.
Note - use of the 'auto-import' extension will also cause read only
data which would normally be placed into the .rdata section to be
placed into the .data section instead. This is in order to work
around a problem with consts that is described here:
http://www.cygwin.com/ml/cygwin/2004-09/msg01101.html
Using 'auto-import' generally will 'just work' -- but sometimes you
may see this message:
"variable '<var>' can't be auto-imported. Please read the
documentation for ld's "--enable-auto-import" for details."
This message occurs when some (sub)expression accesses an address
ultimately given by the sum of two constants (Win32 import tables
only allow one). Instances where this may occur include accesses
to member fields of struct variables imported from a DLL, as well
as using a constant index into an array variable imported from a
DLL. Any multiword variable (arrays, structs, long long, etc) may
trigger this error condition. However, regardless of the exact
data type of the offending exported variable, ld will always detect
it, issue the warning, and exit.
There are several ways to address this difficulty, regardless of
the data type of the exported variable:
One way is to use --enable-runtime-pseudo-reloc switch. This leaves
the task of adjusting references in your client code for runtime
environment, so this method works only when runtime environment
supports this feature.
A second solution is to force one of the 'constants' to be a
variable -- that is, unknown and un-optimizable at compile time.
For arrays, there are two possibilities: a) make the indexee (the
array's address) a variable, or b) make the 'constant' index a
variable. Thus:
extern type extern_array[];
extern_array[1] -->
{ volatile type *t=extern_array; t[1] }
or
extern type extern_array[];
extern_array[1] -->
{ volatile int t=1; extern_array[t] }
For structs (and most other multiword data types) the only option
is to make the struct itself (or the long long, or the ...)
variable:
extern struct s extern_struct;
extern_struct.field -->
{ volatile struct s *t=&extern_struct; t->field }
or
extern long long extern_ll;
extern_ll -->
{ volatile long long * local_ll=&extern_ll; *local_ll }
A third method of dealing with this difficulty is to abandon
'auto-import' for the offending symbol and mark it with
"__declspec(dllimport)". However, in practice that requires using
compile-time #defines to indicate whether you are building a DLL,
building client code that will link to the DLL, or merely
building/linking to a static library. In making the choice
between the various methods of resolving the 'direct address with
constant offset' problem, you should consider typical real-world
usage:
Original:
--foo.h
extern int arr[];
--foo.c
#include "foo.h"
void main(int argc, char **argv){
printf("%d\n",arr[1]);
}
Solution 1:
--foo.h
extern int arr[];
--foo.c
#include "foo.h"
void main(int argc, char **argv){
/* This workaround is for win32 and cygwin; do not "optimize" */
volatile int *parr = arr;
printf("%d\n",parr[1]);
}
Solution 2:
--foo.h
/* Note: auto-export is assumed (no __declspec(dllexport)) */
#if (defined(_WIN32) || defined(__CYGWIN__)) && \
!(defined(FOO_BUILD_DLL) || defined(FOO_STATIC))
#define FOO_IMPORT __declspec(dllimport)
#else
#define FOO_IMPORT
#endif
extern FOO_IMPORT int arr[];
--foo.c
#include "foo.h"
void main(int argc, char **argv){
printf("%d\n",arr[1]);
}
A fourth way to avoid this problem is to re-code your library to
use a functional interface rather than a data interface for the
offending variables (e.g. set_foo() and get_foo() accessor
functions).
--disable-auto-import
Do not attempt to do sophisticated linking of "_symbol" to
"__imp__symbol" for DATA imports from DLLs. [This option is
specific to the i386 PE targeted port of the linker]
--enable-runtime-pseudo-reloc
If your code contains expressions described in --enable-auto-import
section, that is, DATA imports from DLL with non-zero offset, this
switch will create a vector of 'runtime pseudo relocations' which
can be used by runtime environment to adjust references to such
data in your client code. [This option is specific to the i386 PE
targeted port of the linker]
--disable-runtime-pseudo-reloc
Do not create pseudo relocations for non-zero offset DATA imports
from DLLs. [This option is specific to the i386 PE targeted port
of the linker]
--enable-extra-pe-debug
Show additional debug info related to auto-import symbol thunking.
[This option is specific to the i386 PE targeted port of the
linker]
--section-alignment
Sets the section alignment. Sections in memory will always begin
at addresses which are a multiple of this number. Defaults to
0x1000. [This option is specific to the i386 PE targeted port of
the linker]
--stack reserve
--stack reserve,commit
Specify the number of bytes of memory to reserve (and optionally
commit) to be used as stack for this program. The default is 2MB
reserved, 4K committed. [This option is specific to the i386 PE
targeted port of the linker]
--subsystem which
--subsystem which:major
--subsystem which:major.minor
Specifies the subsystem under which your program will execute. The
legal values for which are "native", "windows", "console", "posix",
and "xbox". You may optionally set the subsystem version also.
Numeric values are also accepted for which. [This option is
specific to the i386 PE targeted port of the linker]
The following options set flags in the "DllCharacteristics" field
of the PE file header: [These options are specific to PE targeted
ports of the linker]
--high-entropy-va
--disable-high-entropy-va
Image is compatible with 64-bit address space layout randomization
(ASLR). This option is enabled by default for 64-bit PE images.
This option also implies --dynamicbase and --enable-reloc-section.
--dynamicbase
--disable-dynamicbase
The image base address may be relocated using address space layout
randomization (ASLR). This feature was introduced with MS Windows
Vista for i386 PE targets. This option is enabled by default but
can be disabled via the --disable-dynamicbase option. This option
also implies --enable-reloc-section.
--forceinteg
--disable-forceinteg
Code integrity checks are enforced. This option is disabled by
default.
--nxcompat
--disable-nxcompat
The image is compatible with the Data Execution Prevention. This
feature was introduced with MS Windows XP SP2 for i386 PE targets.
The option is enabled by default.
--no-isolation
--disable-no-isolation
Although the image understands isolation, do not isolate the image.
This option is disabled by default.
--no-seh
--disable-no-seh
The image does not use SEH. No SE handler may be called from this
image. This option is disabled by default.
--no-bind
--disable-no-bind
Do not bind this image. This option is disabled by default.
--wdmdriver
--disable-wdmdriver
The driver uses the MS Windows Driver Model. This option is
disabled by default.
--tsaware
--disable-tsaware
The image is Terminal Server aware. This option is disabled by
default.
--insert-timestamp
--no-insert-timestamp
Insert a real timestamp into the image. This is the default
behaviour as it matches legacy code and it means that the image
will work with other, proprietary tools. The problem with this
default is that it will result in slightly different images being
produced each time the same sources are linked. The option
--no-insert-timestamp can be used to insert a zero value for the
timestamp, this ensuring that binaries produced from identical
sources will compare identically.
If --insert-timestamp is active then the time inserted is either
the time that the linking takes place or, if the
"SOURCE_DATE_EPOCH" environment variable is defined, the number of
seconds since Unix epoch as specified by that variable.
--enable-reloc-section
--disable-reloc-section
Create the base relocation table, which is necessary if the image
is loaded at a different image base than specified in the PE
header. This option is enabled by default.
The C6X uClinux target uses a binary format called DSBT to support
shared libraries. Each shared library in the system needs to have a
unique index; all executables use an index of 0.
--dsbt-size size
This option sets the number of entries in the DSBT of the current
executable or shared library to size. The default is to create a
table with 64 entries.
--dsbt-index index
This option sets the DSBT index of the current executable or shared
library to index. The default is 0, which is appropriate for
generating executables. If a shared library is generated with a
DSBT index of 0, the "R_C6000_DSBT_INDEX" relocs are copied into
the output file.
The --no-merge-exidx-entries switch disables the merging of
adjacent exidx entries in frame unwind info.
--branch-stub
This option enables linker branch relaxation by inserting branch
stub sections when needed to extend the range of branches. This
option is usually not required since C-SKY supports branch and call
instructions that can access the full memory range and branch
relaxation is normally handled by the compiler or assembler.
--stub-group-size=N
This option allows finer control of linker branch stub creation.
It sets the maximum size of a group of input sections that can be
handled by one stub section. A negative value of N locates stub
sections after their branches, while a positive value allows stub
sections to appear either before or after the branches. Values of
1 or -1 indicate that the linker should choose suitable defaults.
The 68HC11 and 68HC12 linkers support specific options to control the
memory bank switching mapping and trampoline code generation.
--no-trampoline
This option disables the generation of trampoline. By default a
trampoline is generated for each far function which is called using
a "jsr" instruction (this happens when a pointer to a far function
is taken).
--bank-window name
This option indicates to the linker the name of the memory region
in the MEMORY specification that describes the memory bank window.
The definition of such region is then used by the linker to compute
paging and addresses within the memory window.
The following options are supported to control handling of GOT
generation when linking for 68K targets.
--got=type
This option tells the linker which GOT generation scheme to use.
type should be one of single, negative, multigot or target. For
more information refer to the Info entry for ld.
The following options are supported to control microMIPS instruction
generation and branch relocation checks for ISA mode transitions when
linking for MIPS targets.
--insn32
--no-insn32
These options control the choice of microMIPS instructions used in
code generated by the linker, such as that in the PLT or lazy
binding stubs, or in relaxation. If --insn32 is used, then the
linker only uses 32-bit instruction encodings. By default or if
--no-insn32 is used, all instruction encodings are used, including
16-bit ones where possible.
--ignore-branch-isa
--no-ignore-branch-isa
These options control branch relocation checks for invalid ISA mode
transitions. If --ignore-branch-isa is used, then the linker
accepts any branch relocations and any ISA mode transition required
is lost in relocation calculation, except for some cases of "BAL"
instructions which meet relaxation conditions and are converted to
equivalent "JALX" instructions as the associated relocation is
calculated. By default or if --no-ignore-branch-isa is used a
check is made causing the loss of an ISA mode transition to produce
an error.
--compact-branches
--no-compact-branches
These options control the generation of compact instructions by the
linker in the PLT entries for MIPS R6.
For the pdp11-aout target, three variants of the output format can be
produced as selected by the following options. The default variant for
pdp11-aout is the --omagic option, whereas for other targets --nmagic
is the default. The --imagic option is defined only for the pdp11-aout
target, while the others are described here as they apply to the
pdp11-aout target.
-N
--omagic
Mark the output as "OMAGIC" (0407) in the a.out header to indicate
that the text segment is not to be write-protected and shared.
Since the text and data sections are both readable and writable,
the data section is allocated immediately contiguous after the text
segment. This is the oldest format for PDP11 executable programs
and is the default for ld on PDP11 Unix systems from the beginning
through 2.11BSD.
-n
--nmagic
Mark the output as "NMAGIC" (0410) in the a.out header to indicate
that when the output file is executed, the text portion will be
read-only and shareable among all processes executing the same
file. This involves moving the data areas up to the first possible
8K byte page boundary following the end of the text. This option
creates a pure executable format.
-z
--imagic
Mark the output as "IMAGIC" (0411) in the a.out header to indicate
that when the output file is executed, the program text and data
areas will be loaded into separate address spaces using the split
instruction and data space feature of the memory management unit in
larger models of the PDP11. This doubles the address space
available to the program. The text segment is again pure,
write-protected, and shareable. The only difference in the output
format between this option and the others, besides the magic
number, is that both the text and data sections start at location
0. The -z option selected this format in 2.11BSD. This option
creates a separate executable format.
--no-omagic
Equivalent to --nmagic for pdp11-aout.
ENVIRONMENT
You can change the behaviour of ld with the environment variables
"GNUTARGET", "LDEMULATION" and "COLLECT_NO_DEMANGLE".
"GNUTARGET" determines the input-file object format if you don't use -b
(or its synonym --format). Its value should be one of the BFD names
for an input format. If there is no "GNUTARGET" in the environment, ld
uses the natural format of the target. If "GNUTARGET" is set to
"default" then BFD attempts to discover the input format by examining
binary input files; this method often succeeds, but there are potential
ambiguities, since there is no method of ensuring that the magic number
used to specify object-file formats is unique. However, the
configuration procedure for BFD on each system places the conventional
format for that system first in the search-list, so ambiguities are
resolved in favor of convention.
"LDEMULATION" determines the default emulation if you don't use the -m
option. The emulation can affect various aspects of linker behaviour,
particularly the default linker script. You can list the available
emulations with the --verbose or -V options. If the -m option is not
used, and the "LDEMULATION" environment variable is not defined, the
default emulation depends upon how the linker was configured.
Normally, the linker will default to demangling symbols. However, if
"COLLECT_NO_DEMANGLE" is set in the environment, then it will default
to not demangling symbols. This environment variable is used in a
similar fashion by the "gcc" linker wrapper program. The default may
be overridden by the --demangle and --no-demangle options.
If the PE/COFF specific --insert-timestamp is active and the
SOURCE_DATE_EPOCH environment variable is defined, then the timestamp
value in this variable will be inserted into the COFF header instead of
the current time.
SEE ALSO
ar(1), nm(1), objcopy(1), objdump(1), readelf(1) and the Info entries
for binutils and ld.
COPYRIGHT
Copyright (c) 1991-2025 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3 or
any later version published by the Free Software Foundation; with no
Invariant Sections, with no Front-Cover Texts, and with no Back-Cover
Texts. A copy of the license is included in the section entitled "GNU
Free Documentation License".
binutils-2.44 2025-02-02 LD(1)
AS(1) Инструменты разработки GNU AS(1)
NAME
AS - переносимый ассемблер GNU.
SYNOPSIS
as [-a[cdghilns][=file]]
[--alternate]
[--compress-debug-sections] [--nocompress-debug-sections]
[-D]
[--dump-config]
[--debug-prefix-map old=new]
[--defsym sym=val]
[--elf-stt-common=[no|yes]]
[--emulation=name]
[-f]
[-g] [--gstabs] [--gstabs+]
[--gdwarf-<N>] [--gdwarf-sections]
[--gdwarf-cie-version=VERSION]
[--generate-missing-build-notes=[no|yes]]
[--gsframe]
[--hash-size=N]
[--help] [--target-help]
[--info] [--no-info]
[-I dir]
[-J]
[-K]
[--keep-locals]
[-L]
[--listing-lhs-width=NUM]
[--listing-lhs-width2=NUM]
[--listing-rhs-width=NUM]
[--listing-cont-lines=NUM]
[--multibyte-handling=[allow|warn|warn-sym-only]]
[--no-pad-sections]
[-o objfile] [-R]
[--scfi=experimental]
[--sectname-subst]
[--size-check=[error|warning]]
[--statistics]
[-v] [-version] [--version]
[-W] [--no-warn] [--warn] [--fatal-warnings]
[-w] [-x]
[-Z] [@FILE]
[target-options]
[--|files ...]
TARGET
Опции для целевой платформы AArch64:
[-EB|-EL]
[-mabi=ABI]
Опции для целевой платформы Alpha:
[-mcpu]
[-mdebug | -no-mdebug]
[-replace | -noreplace]
[-relax] [-g] [-Gsize]
[-F] [-32addr]
Опции для целевой платформы ARC:
[-mcpu=cpu]
[-mA6|-mARC600|-mARC601|-mA7|-mARC700|-mEM|-mHS]
[-mcode-density]
[-mrelax]
[-EB|-EL]
Опции для целевой платформы ARM:
[-mcpu=processor[+extension...]]
[-march=architecture[+extension...]]
[-mfpu=floating-point-format]
[-mfloat-abi=abi]
[-meabi=ver]
[-mthumb]
[-EB|-EL]
[-mapcs-32|-mapcs-26|-mapcs-float|
-mapcs-reentrant]
[-mthumb-interwork] [-k]
Опции для целевой платформы Blackfin:
[-mcpu=processor[-sirevision]]
[-mfdpic]
[-mno-fdpic]
[-mnopic]
Опции для целевой платформы BPF:
[-EL] [-EB]
Опции для целевой платформы CRIS:
[--underscore | --no-underscore]
[--pic] [-N]
[--emulation=criself | --emulation=crisaout]
[--march=v0_v10 | --march=v10 | --march=v32 |
--march=common_v10_v32]
Опции для целевой платформы C-SKY:
[-march=arch] [-mcpu=cpu]
[-EL] [-mlittle-endian] [-EB] [-mbig-endian]
[-fpic] [-pic]
[-mljump] [-mno-ljump]
[-force2bsr] [-mforce2bsr] [-no-force2bsr] [-mno-force2bsr]
[-jsri2bsr] [-mjsri2bsr] [-no-jsri2bsr ] [-mno-jsri2bsr]
[-mnolrw ] [-mno-lrw]
[-melrw] [-mno-elrw]
[-mlaf ] [-mliterals-after-func]
[-mno-laf] [-mno-literals-after-func]
[-mlabr] [-mliterals-after-br]
[-mno-labr] [-mnoliterals-after-br]
[-mistack] [-mno-istack]
[-mhard-float] [-mmp] [-mcp] [-mcache]
[-msecurity] [-mtrust]
[-mdsp] [-medsp] [-mvdsp]
Опции для целевой платформы D10V:
[-O]
Опции для целевой платформы D30V:
[-O|-n|-N]
Опции для целевой платформы EPIPHANY:
[-mepiphany|-mepiphany16]
Опции для целевой платформы H8/300:
[-h-tick-hex]
Опции для целевой платформы i386:
[--32|--x32|--64] [-n]
[-march=CPU[+EXTENSION...]] [-mtune=CPU]
Опции для целевой платформы IA-64:
[-mconstant-gp|-mauto-pic]
[-milp32|-milp64|-mlp64|-mp64]
[-mle|mbe]
[-mtune=itanium1|-mtune=itanium2]
[-munwind-check=warning|-munwind-check=error]
[-mhint.b=ok|-mhint.b=warning|-mhint.b=error]
[-x|-xexplicit] [-xauto] [-xdebug]
Опции для целевой платформы IP2K:
[-mip2022|-mip2022ext]
Опции для целевой платформы M32C:
[-m32c|-m16c] [-relax] [-h-tick-hex]
Опции для целевой платформы M32R:
[--m32rx|--[no-]warn-explicit-parallel-conflicts|
--W[n]p]
Опции для целевой платформы M680X0:
[-l] [-m68000|-m68010|-m68020|...]
Опции для целевой платформы M68HC11:
[-m68hc11|-m68hc12|-m68hcs12|-mm9s12x|-mm9s12xg]
[-mshort|-mlong]
[-mshort-double|-mlong-double]
[--force-long-branches] [--short-branches]
[--strict-direct-mode] [--print-insn-syntax]
[--print-opcodes] [--generate-example]
Опции для целевой платформы MCORE:
[-jsri2bsr] [-sifilter] [-relax]
[-mcpu=[210|340]]
Опции для целевой платформы Meta:
[-mcpu=cpu] [-mfpu=cpu] [-mdsp=cpu] Опции для целевой платформы MICROBLAZE:
[-mlittle-endian] [-mbig-endian]
Опции для целевой платформы MIPS:
[-nocpp] [-EL] [-EB] [-O[optimization level]]
[-g[debug level]] [-G num] [-KPIC] [-call_shared]
[-non_shared] [-xgot [-mvxworks-pic]
[-mabi=ABI] [-32] [-n32] [-64] [-mfp32] [-mgp32]
[-mfp64] [-mgp64] [-mfpxx]
[-modd-spreg] [-mno-odd-spreg]
[-march=CPU] [-mtune=CPU] [-mips1] [-mips2]
[-mips3] [-mips4] [-mips5] [-mips32] [-mips32r2]
[-mips32r3] [-mips32r5] [-mips32r6] [-mips64] [-mips64r2]
[-mips64r3] [-mips64r5] [-mips64r6]
[-construct-floats] [-no-construct-floats]
[-mignore-branch-isa] [-mno-ignore-branch-isa]
[-mnan=encoding]
[-trap] [-no-break] [-break] [-no-trap]
[-mips16] [-no-mips16]
[-mmips16e2] [-mno-mips16e2]
[-mmicromips] [-mno-micromips]
[-msmartmips] [-mno-smartmips]
[-mips3d] [-no-mips3d]
[-mdmx] [-no-mdmx]
[-mdsp] [-mno-dsp]
[-mdspr2] [-mno-dspr2]
[-mdspr3] [-mno-dspr3]
[-mmsa] [-mno-msa]
[-mxpa] [-mno-xpa]
[-mmt] [-mno-mt]
[-mmcu] [-mno-mcu]
[-mcrc] [-mno-crc]
[-mginv] [-mno-ginv]
[-mloongson-mmi] [-mno-loongson-mmi]
[-mloongson-cam] [-mno-loongson-cam]
[-mloongson-ext] [-mno-loongson-ext]
[-mloongson-ext2] [-mno-loongson-ext2]
[-minsn32] [-mno-insn32]
[-mfix7000] [-mno-fix7000]
[-mfix-rm7000] [-mno-fix-rm7000]
[-mfix-vr4120] [-mno-fix-vr4120]
[-mfix-vr4130] [-mno-fix-vr4130]
[-mfix-r5900] [-mno-fix-r5900]
[-mdebug] [-no-mdebug]
[-mpdr] [-mno-pdr]
Опции для целевой платформы MMIX:
[--fixed-special-register-names] [--globalize-symbols]
[--gnu-syntax] [--relax] [--no-predefined-symbols]
[--no-expand] [--no-merge-gregs] [-x]
[--linker-allocated-gregs]
Опции для целевой платформы NDS32:
[-EL] [-EB] [-O] [-Os] [-mcpu=cpu]
[-misa=isa] [-mabi=abi] [-mall-ext]
[-m[no-]16-bit] [-m[no-]perf-ext] [-m[no-]perf2-ext]
[-m[no-]string-ext] [-m[no-]dsp-ext] [-m[no-]mac] [-m[no-]div]
[-m[no-]audio-isa-ext] [-m[no-]fpu-sp-ext] [-m[no-]fpu-dp-ext]
[-m[no-]fpu-fma] [-mfpu-freg=FREG] [-mreduced-regs]
[-mfull-regs] [-m[no-]dx-regs] [-mpic] [-mno-relax]
[-mb2bb]
Опции для целевой платформы PDP11:
[-mpic|-mno-pic] [-mall] [-mno-extensions]
[-mextension|-mno-extension]
[-mcpu] [-mmachine]
Опции для целевой платформы picoJava:
[-mb|-me]
Опции для целевой платформы PowerPC:
[-a32|-a64]
[-mpwrx|-mpwr2|-mpwr|-m601|-mppc|-mppc32|-m603|-m604|-m403|-m405|
-m440|-m464|-m476|-m7400|-m7410|-m7450|-m7455|-m750cl|-mgekko|
-mbroadway|-mppc64|-m620|-me500|-e500x2|-me500mc|-me500mc64|-me5500|
-me6500|-mppc64bridge|-mbooke|-mpower4|-mpwr4|-mpower5|-mpwr5|-mpwr5x|
-mpower6|-mpwr6|-mpower7|-mpwr7|-mpower8|-mpwr8|-mpower9|-mpwr9-ma2|
-mcell|-mspe|-mspe2|-mtitan|-me300|-mcom]
[-many] [-maltivec|-mvsx|-mhtm|-mvle]
[-mregnames|-mno-regnames]
[-mrelocatable|-mrelocatable-lib|-K PIC] [-memb]
[-mlittle|-mlittle-endian|-le|-mbig|-mbig-endian|-be]
[-msolaris|-mno-solaris]
[-nops=count]
Опции для целевой платформы PRU:
[-link-relax]
[-mnolink-relax]
[-mno-warn-regname-label]
Опции для целевой платформы RISC-V:
[-fpic|-fPIC|-fno-pic]
[-march=ISA]
[-mabi=ABI]
[-mlittle-endian|-mbig-endian]
Опции для целевой платформы RL78:
[-mg10]
[-m32bit-doubles|-m64bit-doubles]
Опции для целевой платформы RX:
[-mlittle-endian|-mbig-endian]
[-m32bit-doubles|-m64bit-doubles]
[-muse-conventional-section-names]
[-msmall-data-limit]
[-mpid]
[-mrelax]
[-mint-register=number]
[-mgcc-abi|-mrx-abi]
Опции для целевой платформы s390:
[-m31|-m64] [-mesa|-mzarch] [-march=CPU]
[-mregnames|-mno-regnames]
[-mwarn-areg-zero]
[-mwarn-regtype-mismatch=strict
-mwarn-regtype-mismatch=relaxed
-mwarn-regtype-mismatch=no
-mno-warn-regtype-mismatch]
Опции для целевой платформы SCORE:
[-EB][-EL][-FIXDD][-NWARN]
[-SCORE5][-SCORE5U][-SCORE7][-SCORE3]
[-march=score7][-march=score3]
[-USE_R1][-KPIC][-O0][-G num][-V]
Опции для целевой платформы SPARC:
[-Av6|-Av7|-Av8|-Aleon|-Asparclet|-Asparclite
-Av8plus|-Av8plusa|-Av8plusb|-Av8plusc|-Av8plusd
-Av8plusv|-Av8plusm|-Av9|-Av9a|-Av9b|-Av9c
-Av9d|-Av9e|-Av9v|-Av9m|-Asparc|-Asparcvis
-Asparcvis2|-Asparcfmaf|-Asparcima|-Asparcvis3
-Asparcvisr|-Asparc5]
[-xarch=v8plus|-xarch=v8plusa]|-xarch=v8plusb|-xarch=v8plusc
-xarch=v8plusd|-xarch=v8plusv|-xarch=v8plusm|-xarch=v9
-xarch=v9a|-xarch=v9b|-xarch=v9c|-xarch=v9d|-xarch=v9e
-xarch=v9v|-xarch=v9m|-xarch=sparc|-xarch=sparcvis
-xarch=sparcvis2|-xarch=sparcfmaf|-xarch=sparcima
-xarch=sparcvis3|-xarch=sparcvisr|-xarch=sparc5
-bump]
[-32|-64]
[--enforce-aligned-data][--dcti-couples-detect]
Опции для целевой платформы TIC54X:
[-mcpu=54[123589]|-mcpu=54[56]lp] [-mfar-mode|-mf]
[-merrors-to-file <filename>|-me <filename>]
Опции для целевой платформы TIC6X:
[-march=arch] [-mbig-endian|-mlittle-endian]
[-mdsbt|-mno-dsbt] [-mpid=no|-mpid=near|-mpid=far]
[-mpic|-mno-pic]
Опции для целевой платформы TILE-Gx:
[-m32|-m64][-EB][-EL]
Опции для целевой платформы Visium:
[-mtune=arch]
Опции для целевой платформы Xtensa:
[--[no-]text-section-literals] [--[no-]auto-litpools]
[--[no-]absolute-literals]
[--[no-]target-align] [--[no-]longcalls]
[--[no-]transform]
[--rename-section oldname=newname]
[--[no-]trampolines]
[--abi-windowed|--abi-call0]
Опции для целевой платформы Z80:
[-march=CPU[-EXT][+EXT]]
[-local-prefix=PREFIX]
[-colonless]
[-sdcc]
[-fp-s=FORMAT]
[-fp-d=FORMAT]
DESCRIPTION
GNU as представляет собой семейство ассемблеров. Если вы используете (или использовали) ассемблер GNU на одной архитектуре, вы обнаружите достаточно похожую среду при работе с ним на другой архитектуре. Каждая версия имеет много общего с остальными, включая форматы объектных файлов, большинство директив ассемблера (часто называемых псевдооперациями) и синтаксис ассемблера.
as в первую очередь предназначен для сборки вывода компилятора GNU C "gcc" для использования связывателем "ld". Тем не менее, мы постарались сделать так, чтобы as правильно собирал всё, что могли бы собрать другие ассемблеры для той же машины. Любые исключения документированы явно. Это не означает, что as всегда использует тот же синтаксис, что и другой ассемблер для той же архитектуры; например, мы знаем о нескольких несовместимых версиях синтаксиса языка ассемблирования 680x0.
Каждый раз, когда вы запускаете as, он собирает ровно одну исходную программу. Исходная программа состоит из одного или нескольких файлов. (Стандартный ввод также является файлом.)
Вы передаёте as командную строку, содержащую нулевое или несколько имён входных файлов. Входные файлы читаются (от левого имени файла к правому). Аргумент командной строки (в любом положении), не имеющий специального значения, считается именем входного файла.
Если вы не указываете as никаких имён файлов, он попытается прочитать один входной файл из стандартного ввода as, который обычно является вашим терминалом. Вам может потребоваться ввести ctl-D, чтобы сообщить as, что больше нет программы для сборки.
Используйте --, если вам нужно явно указать стандартный входной файл в вашей командной строке.
Если исходный код пуст, as генерирует небольшой пустой объектный файл.
as может выводить предупреждения и сообщения об ошибках в стандартный файл ошибок (обычно ваш терминал). Это не должно происходить, когда компилятор запускает as автоматически. Предупреждения сообщают об предположении, сделанном для того, чтобы as мог продолжить сборку проблемной программы; ошибки сообщают о серьёзной проблеме, которая останавливает сборку.
Если вы вызываете as через компилятор GNU C, вы можете использовать опцию -Wa для передачи аргументов ассемблеру. Аргументы ассемблера должны быть разделены друг от друга (и от -Wa) запятыми. Например:
gcc -c -g -O -Wa,-alh,-L file.c
Это передаёт ассемблеру две опции: -alh (вывод списка в стандартный вывод с исходным кодом высокого уровня и ассемблирования) и -L (сохранение локальных символов в таблице символов).
Обычно вам не нужно использовать этот механизм -Wa, поскольку многие опции командной строки компилятора автоматически передаются ассемблеру. (Вы можете вызвать драйвер компилятора GNU с опцией -v, чтобы увидеть точно, какие опции он передаёт каждому этапу компиляции, включая ассемблер.)
OPTIONS
@file
Прочитать опции командной строки из файла. Опции, прочитанные из файла, вставляются на место исходной опции @file. Если файл не существует или не может быть прочитан, опция будет обработана буквально, без удаления.
Опции в файле разделены пробелами. Символ пробела можно включить в опцию, заключая всю опцию в одинарные или двойные кавычки. Любые символы (включая обратную косую черту) можно включить, предваряя символ, подлежащий включению, обратной косой чертой. Файл может сам содержать дополнительные опции @file; такие опции будут обработаны рекурсивно.
-a[cdghilmns]
Включить списки различными способами:
-ac пропустить ложные условные конструкции
-ad пропустить директивы отладки
-ag включить общую информацию, такую как версия as и переданные опции
-ah включить исходный код высокого уровня
-al включить ассемблирование
-ali
включить ассемблирование с ginsn
-am включить расширения макросов
-an пропустить обработку форм
-as включить символы
=file
установить имя файла списка
Вы можете комбинировать эти опции; например, используйте -aln для списка ассемблирования без обработки форм. Опция =file, если используется, должна быть последней. Сама по себе -a по умолчанию эквивалентна -ahls.
--alternate
Начать в альтернативном режиме макросов.
--compress-debug-sections
Сжать разделы отладки DWARF с использованием zlib с SHF_COMPRESSED из ELF ABI. Полученный объектный файл может быть несовместим с более старыми связывателями и утилитами объектных файлов. Обратите внимание, что если сжатие сделает раздел больше, он не будет сжат.
--compress-debug-sections=none
--compress-debug-sections=zlib
--compress-debug-sections=zlib-gnu
--compress-debug-sections=zlib-gabi
--compress-debug-sections=zstd
Эти опции управляют сжатием разделов отладки DWARF.
--compress-debug-sections=none эквивалентно
--nocompress-debug-sections. --compress-debug-sections=zlib и
--compress-debug-sections=zlib-gabi эквивалентны
--compress-debug-sections. --compress-debug-sections=zlib-gnu
сжимает разделы отладки DWARF с использованием устаревшего формата zlib-gnu.
Разделы отладки переименовываются, начиная с .zdebug.
--compress-debug-sections=zstd сжимает разделы отладки DWARF с использованием zstd.
Обратите внимание - если сжатие сделает раздел больше, он не будет сжат и переименован.
--nocompress-debug-sections
Не сжимать разделы отладки DWARF. Это обычно значение по умолчанию для всех целей, кроме x86/x86_64, но опция конфигурации может переопределить это.
-D Включить отладку в целевых специфических бэкендах, если это поддерживается.
В противном случае игнорируется. Даже если игнорируется, эта опция принимается для совместимости скриптов с вызовами других ассемблеров.
--debug-prefix-map old=new
При сборке файлов в каталоге old записывать информацию отладки, описывающую их как в new.
--defsym sym=value
Определить символ sym как value перед сборкой входного файла.
value должно быть целочисленной константой. Как в C, ведущий 0x указывает на шестнадцатеричное значение, а ведущий 0 - на восьмеричное. Значение символа может быть переопределено внутри исходного файла с помощью псевдооперации ".set".
--dump-config
Вывести, как настроен ассемблер, и выйти.
--elf-stt-common=no
--elf-stt-common=yes
Эти опции управляют тем, должен ли ассемблер ELF генерировать общие символы с типом "STT_COMMON". Значение по умолчанию можно контролировать опцией конфигурации --enable-elf-stt-common.
--emulation=name
Если ассемблер настроен на поддержку нескольких разных целевых конфигураций, эта опция может быть использована для выбора желаемой формы.
-f "быстро" - пропустить предобработку пробелов и комментариев (предположить, что исходный код является выводом компилятора).
-g
--gen-debug
Генерировать информацию отладки для каждой строки исходного кода ассемблера с использованием предпочтительного формата отладки для цели. В настоящее время это означает либо STABS, либо ECOFF, либо DWARF2. Когда формат отладки - DWARF, разделы ".debug_info" и ".debug_line" генерируются только в том случае, если файл сборки не генерирует их сам.
--gstabs
Генерировать информацию отладки stabs для каждой строки ассемблера. Это может помочь в отладке кода ассемблера, если отладчик может обработать это.
--gstabs+
Генерировать информацию отладки stabs для каждой строки ассемблера с расширениями GNU, которые, вероятно, может обработать только gdb, и которые могут привести к сбою других отладчиков или отказу от чтения вашей программы. Это может помочь в отладке кода ассемблера. В настоящее время единственное расширение GNU - это местоположение текущей рабочей директории во время сборки.
--gdwarf-2
Генерировать информацию отладки DWARF2 для каждой строки ассемблера.
Это может помочь в отладке кода ассемблера, если отладчик может обработать это. Обратите внимание - эта опция поддерживается только некоторыми целями, не всеми.
--gdwarf-3
Эта опция аналогична --gdwarf-2, за исключением того, что она позволяет возможность генерации дополнительной информации отладки в соответствии с версией 3 спецификации DWARF. Обратите внимание - включение этой опции не гарантирует генерацию дополнительной информации, выбор зависит от цели.
--gdwarf-4
Эта опция аналогична --gdwarf-2, за исключением того, что она позволяет возможность генерации дополнительной информации отладки в соответствии с версией 4 спецификации DWARF. Обратите внимание - включение этой опции не гарантирует генерацию дополнительной информации, выбор зависит от цели.
--gdwarf-5
Эта опция аналогична --gdwarf-2, за исключением того, что она позволяет возможность генерации дополнительной информации отладки в соответствии с версией 5 спецификации DWARF. Обратите внимание - включение этой опции не гарантирует генерацию дополнительной информации, выбор зависит от цели.
--gdwarf-sections
Вместо создания раздела .debug_line создать серию разделов .debug_line.foo, где foo - имя соответствующего раздела кода. Например, раздел кода, называемый .text.func, будет иметь информацию о номерах строк dwarf в разделе .debug_line.text.func. Если раздел кода называется просто .text, то раздел отладки строк будет называться просто .debug_line без суффикса.
--gdwarf-cie-version=version
Управлять версией записей общей информации DWARF (CIE). Когда эта опция не указана, значение по умолчанию - версия 1, хотя некоторые цели могут изменить это значение по умолчанию. Другие возможные значения для version - 3 или 4.
--generate-missing-build-notes=yes
--generate-missing-build-notes=no
Эти опции управляют тем, должен ли ассемблер ELF генерировать заметки атрибутов сборки GNU, если они отсутствуют в исходных файлах.
Значение по умолчанию можно контролировать опцией конфигурации --enable-generate-build-notes.
--gsframe
--gsframe
Создать раздел .sframe из директив CFI.
--hash-size N
Игнорируется. Поддерживается для совместимости командной строки с другими ассемблерами.
--help
Вывести сводку опций командной строки и выйти.
--target-help
Вывести сводку всех целевых специфических опций и выйти.
--info
Не подавлять информационные сообщения.
--no-info
Подавлять информационные сообщения.
-I dir
Добавить каталог dir в список поиска для директив ".include".
-J Не предупреждать о переполнении знакового типа.
-K Выдавать предупреждения, когда таблицы различий изменяются для длинных смещений.
-L
--keep-locals
Сохранять (в таблице символов) локальные символы. Эти символы начинаются с системно-специфичных префиксов локальных меток, обычно .L для систем ELF или L для традиционных систем a.out.
--listing-lhs-width=number
Установить максимальную ширину, в словах, столбца выходных данных для списка ассемблера на number.
--listing-lhs-width2=number
Установить максимальную ширину, в словах, столбца выходных данных для продолжительных строк в списке ассемблера на number.
--listing-rhs-width=number
Установить максимальную ширину входной строки источника, отображаемой в списке, на number байт.
--listing-cont-lines=number
Установить максимальное количество строк, выводимых в списке для одной строки ввода, на number + 1.
--multibyte-handling=allow
--multibyte-handling=warn
--multibyte-handling=warn-sym-only
--multibyte-handling=warn_sym_only
Управляет тем, как ассемблер обрабатывает многобайтовые символы во входе. Значение по умолчанию (которое можно восстановить с помощью аргумента allow) - разрешить такие символы без жалоб. Использование аргумента warn заставит ассемблер генерировать предупреждающее сообщение при обнаружении любого многобайтового символа. Использование warn-sym-only приведёт к генерации предупреждения только когда определяется символ с именем, содержащим многобайтовые символы.
(Ссылки на неопределённые символы предупреждения не генерируют).
--no-pad-sections
Не заставлять ассемблер дополнять концы выходных разделов до выравнивания раздела. Значение по умолчанию - дополнять разделы, но это может тратить пространство, которое может потребоваться на целях с жёсткими ограничениями памяти.
-o objfile
Назвать выходной объектный файл as objfile.
-R Сложить раздел данных в раздел текста.
--reduce-memory-overheads
Игнорируется. Поддерживается для совместимости с инструментами, которые передают ту же опцию и ассемблеру, и связывателю.
--scfi=experimental
Эта опция управляет тем, должен ли ассемблер синтезировать CFI для рукописного ввода. Если вход уже содержит некоторые синтезируемые директивы CFI, ассемблер игнорирует их и выводит предупреждение. Обратите внимание, что "--scfi=experimental" не предназначен для кода, генерируемого компилятором, включая встроенный ассемблер. Эта экспериментальная поддержка находится в разработке. Поддерживается только ABI System V AMD64.
Каждая входная функция в ассемблере должна начинаться с директивы ".type" и идеально закрываться директивой ".size". При использовании SCFI каждая директива ".type" побуждает GAS начать новый FDE (запись дескриптора функции). Это подразумевает, что с каждой директивой ".type" предыдущий блок инструкций, если он есть, завершается как отдельный FDE.
--sectname-subst
Учитывать последовательности подстановки в именах разделов.
--size-check=error
--size-check=warning
Выдавать ошибку или предупреждение для недействительной директивы ELF .size.
--statistics
Вывести максимальное пространство (в байтах) и общее время (в секундах), использованное сборкой.
--strip-local-absolute
Удалить локальные абсолютные символы из исходящей таблицы символов.
-v
-version
Вывести версию as.
--version
Вывести версию as и выйти.
-W
--no-warn
Подавлять сообщения предупреждений.
--warn
Не подавлять сообщения предупреждений или не рассматривать их как ошибки.
--fatal-warnings
Рассматривать предупреждения как ошибки.
-w Игнорируется.
-x Игнорируется.
-Z Генерировать объектный файл даже после ошибок.
-- | files ...
Стандартный ввод или исходные файлы для сборки.
Следующие опции доступны, когда as настроен для 64-разрядного режима архитектуры ARM (AArch64).
-EB Эта опция указывает, что выход, генерируемый ассемблером, должен быть помечен как закодированный для процессора с порядком байтов big-endian.
-EL Эта опция указывает, что выход, генерируемый ассемблером, должен быть помечен как закодированный для процессора с порядком байтов little-endian.
-mabi=abi
Указать, какой ABI использует исходный код. Принимаемые аргументы: "ilp32" и "lp64", которые определяют генерируемый объектный файл в форматах ELF32 и ELF64 соответственно. Значение по умолчанию - "lp64".
-mcpu=processor[+extension...]
Эта опция указывает целевой процессор. Ассемблер выдаст сообщение об ошибке, если будет предпринята попытка собрать инструкцию, которая не выполнится на целевом процессоре. Принимаемые имена процессоров: "cortex-a34",
"cortex-a35", "cortex-a53", "cortex-a55", "cortex-a57",
"cortex-a65", "cortex-a65ae", "cortex-a72", "cortex-a73",
"cortex-a75", "cortex-a76", "cortex-a76ae", "cortex-a77",
"cortex-a78", "cortex-a78ae", "cortex-a78c", "cortex-a510",
"cortex-a520", "cortex-a710", "cortex-a720", "ares", "exynos-m1",
"falkor", "neoverse-n1", "neoverse-n2", "neoverse-e1",
"neoverse-v1", "qdf24xx", "saphira", "thunderx", "vulcan", "xgene1"
"xgene2", "cortex-r82", "cortex-x1", "cortex-x2", "cortex-x3", и
"cortex-x4". Специальное имя "all" может быть использовано, чтобы разрешить ассемблеру принимать инструкции, действительные для любого поддерживаемого процессора, включая все необязательные расширения.
Помимо базового набора инструкций, ассемблеру можно указать принимать или ограничивать различные мнемоники расширений.
Если некоторые реализации определённого процессора могут иметь расширение, то эти расширения автоматически включаются.
Следовательно, вам обычно не нужно указывать дополнительные расширения.
-march=architecture[+extension...]
Эта опция указывает целевую архитектуру. Ассемблер выдаст сообщение об ошибке, если будет предпринята попытка собрать инструкцию, которая не выполнится на целевой архитектуре. Принимаемые имена архитектур: "armv8-a",
"armv8.1-a", "armv8.2-a", "armv8.3-a", "armv8.4-a" "armv8.5-a",
"armv8.6-a", "armv8.7-a", "armv8.8-a", "armv8.9-a", "armv8-r",
"armv9-a", "armv9.1-a", "armv9.2-a", "armv9.3-a", "armv9.4-a" и
"armv9.5-a".
Если указаны обе -mcpu и -march, ассемблер использует значение для -mcpu. Если ни одна не указана, ассемблер по умолчанию использует -mcpu=all.
Опция архитектуры может быть расширена теми же опциями набора инструкций, что и опция -mcpu. В отличие от -mcpu,
расширения не всегда включены по умолчанию.
-mverbose-error
Эта опция включает подробные сообщения об ошибках для AArch64 gas. Эта опция включена по умолчанию.
-mno-verbose-error
Эта опция отключает подробные сообщения об ошибках в AArch64 gas.
Следующие опции доступны, когда as настроен для процессора Alpha.
-mcpu
Эта опция указывает целевой процессор. Если будет предпринята попытка собрать инструкцию, которая не выполнится на целевом процессоре, ассемблер может либо развернуть инструкцию как макрос, либо выдать сообщение об ошибке. Эта опция эквивалентна директиве ".arch".
Принимаемые имена процессоров: 21064, "21064a",
21066, 21068, 21164, "21164a", "21164pc", 21264, "21264a",
"21264b", "ev4", "ev5", "lca45", "ev5", "ev56", "pca56", "ev6",
"ev67", "ev68". Специальное имя "all" может быть использовано, чтобы разрешить ассемблеру принимать инструкции, действительные для любого процессора Alpha.
Для поддержки существующей практики в OSF/1 относительно ".arch" и существующей практики в MILO (загрузчик ARC Linux), нумерациированные имена процессоров (например, 21064) включают процессор-специфические инструкции PALcode, в то время как "электро-власические" имена (например, "ev4") не включают.
-mdebug
-no-mdebug
Включить или отключить генерацию инкапсуляции ".mdebug" для директив stabs и дескрипторов процедур. Значение по умолчанию - автоматически включить ".mdebug", когда видна первая директива stabs.
-relax
Эта опция заставляет все релокации помещаться в объектный файл,
вместо экономии пространства и разрешения некоторых релокаций во время сборки. Обратите внимание, что эта опция не распространяет всю арифметику символов в объектный файл, поскольку не вся арифметика символов может быть представлена. Тем не менее, опция может быть полезной в конкретных приложениях.
-replace
-noreplace
Включить или отключить оптимизацию вызовов процедур, как во время сборки, так и во время связывания. Эти опции доступны только для целей VMS, и "-replace" - значение по умолчанию. См. раздел 1.4.1 руководства утилиты связывателя OpenVMS.
-g Эта опция используется, когда компилятор генерирует информацию отладки.
Когда gcc использует mips-tfile для генерации информации отладки для ECOFF, локальные метки должны передаваться в объектный файл.
В противном случае эта опция не оказывает влияния.
-Gsize
Локальный общий символ, больший, чем size, размещается в ".bss", в то время как меньшие символы размещаются в ".sbss".
-F
-32addr
Эти опции игнорируются для обратной совместимости.
Следующие опции доступны, когда as настроен для процессора ARC.
-mcpu=cpu
Эта опция выбирает вариант ядра процессора.
-EB | -EL
Выбрать порядок байтов big-endian (-EB) или little-endian (-EL).
Следующие опции доступны, когда as настроен для семейства процессоров ARM.
-mcpu=processor[+extension...]
Указать, какой вариант процессора ARM является целью.
-march=architecture[+extension...]
Указать, какая вариант архитектуры ARM используется целью.
-mfpu=floating-point-format
Выбрать, какая архитектура с плавающей точкой является целью.
-mfloat-abi=abi
Выбрать, какой ABI с плавающей точкой используется.
-mthumb
Включить декодирование только инструкций Thumb.
-mapcs-32 | -mapcs-26 | -mapcs-float | -mapcs-reentrant
Выбрать, какая конвенция вызова процедур используется.
-EB | -EL
Выбрать порядок байтов big-endian (-EB) или little-endian (-EL).
-mthumb-interwork
Указать, что код был сгенерирован с учётом взаимодействия между Thumb и ARM-кодом.
-mccs
Включить режим совместимости синтаксиса сборки CodeComposer Studio.
-k Указать, что сгенерирован PIC-код.
Следующие опции доступны, когда as настроен для семейства процессоров Blackfin.
-mcpu=processor[-sirevision]
Эта опция указывает целевой процессор. Опциональный sirevision не используется в ассемблере. Он здесь для того, чтобы GCC мог легко передавать свою опцию "-mcpu=". Ассемблер выдаст сообщение об ошибке, если будет предпринята попытка собрать инструкцию, которая не выполнится на целевом процессоре. Принимаемые имена процессоров: "bf504", "bf506", "bf512", "bf514",
"bf516", "bf518", "bf522", "bf523", "bf524", "bf525", "bf526",
"bf527", "bf531", "bf532", "bf533", "bf534", "bf535" (ещё не реализовано), "bf536", "bf537", "bf538", "bf539", "bf542",
"bf542m", "bf544", "bf544m", "bf547", "bf547m", "bf548", "bf548m",
"bf549", "bf549m", "bf561", и "bf592".
-mfdpic
Собрать для ABI FDPIC.
-mno-fdpic
-mnopic
Отключить -mfdpic.
Следующие опции доступны, когда as настроен для семейства процессоров BPF ядра Linux.
@chapter BPF Dependent Features
BPF Options
-EB Эта опция указывает, что ассемблер должен генерировать eBPF с порядком байтов big-endian.
-EL Эта опция указывает, что ассемблер должен генерировать eBPF с порядком байтов little-endian.
-mdialect=dialect
Эта опция указывает диалект языка ассемблирования, который следует распознавать при сборке. Ассемблер поддерживает нормальный и pseudoc.
-misa-spec=spec
Эта опция указывает версию набора инструкций BPF, которая должна использоваться при сборке. Поддерживаемые версии набора инструкций BPF: v1 v2, v3 и
v4.
Значение xbpf можно указать, чтобы распознавать дополнительные инструкции, используемые GCC для целей тестирования. Но имейте в виду, что это не действительный BPF.
-mno-relax
Эта опция говорит ассемблеру не расслаблять инструкции.
Обратите внимание, что если опция эндианности не указана в командной строке, используется эндианность хоста. См. страницы info для документации по опциям, специфичным для CRIS.
Следующие опции доступны, когда as настроен для семейства процессоров C-SKY.
-march=archname
Собрать для архитектуры archname. Опция --help перечисляет допустимые значения для archname.
-mcpu=cpuname
Собрать для архитектуры cpuname. Опция --help перечисляет допустимые значения для cpuname.
-EL
-mlittle-endian
Генерировать выход с порядком байтов little-endian.
-EB
-mbig-endian
Генерировать выход с порядком байтов big-endian.
-fpic
-pic
Генерировать позиционно-независимый код.
-mljump
-mno-ljump
Включить/отключить преобразование коротких инструкций ветвления "jbf", "jbt" и "jbr" в "jmpi". Эта опция предназначена только для процессоров V2. Она игнорируется для целей CK801 и CK802, которые не поддерживают инструкцию "jmpi", и включена по умолчанию для других процессоров.
-mbranch-stub
-mno-branch-stub
Пропускать релокации "R_CKCORE_PCREL_IMM26BY2" для инструкций "bsr" в связыватель.
Эта опция доступна только для голых целей ELF V2 C-SKY и включена по умолчанию. Она не может быть использована в коде, который будет динамически связан с разделяемыми библиотеками.
-force2bsr
-mforce2bsr
-no-force2bsr
-mno-force2bsr
Включить/отключить преобразование инструкций "jbsr" в "bsr".
Эта опция всегда включена (и -mno-force2bsr игнорируется) для целей CK801/CK802. Она также всегда включена, когда действует -mbranch-stub.
-jsri2bsr
-mjsri2bsr
-no-jsri2bsr
-mno-jsri2bsr
Включить/отключить преобразование инструкций "jsri" в "bsr".
Эта опция включена по умолчанию.
-mnolrw
-mno-lrw
Включить/отключить преобразование инструкций "lrw" в пару "movih"/"ori".
-melrw
-mno-elrw
Включить/отключить расширенные инструкции "lrw". Эта опция включена по умолчанию для процессоров серии CK800.
-mlaf
-mliterals-after-func
-mno-laf
-mno-literals-after-func
Включить/отключить размещение пулов литералов после каждой функции.
-mlabr
-mliterals-after-br
-mno-labr
-mnoliterals-after-br
Включить/отключить размещение пулов литералов после безусловных ветвлений. Эта опция включена по умолчанию.
-mistack
-mno-istack
Включить/отключить инструкции стека прерываний. Эта опция включена по умолчанию для процессоров CK801, CK802 и CK802.
Следующие опции явно включают определённые необязательные инструкции.
Эти функции также включаются неявно при использовании "-mcpu=" для указания процессора, который их поддерживает.
-mhard-float
Включить инструкции с жёсткой плавающей точкой.
-mmp
Включить инструкции для многопроцессорных систем.
-mcp
Включить инструкции сопроцессора.
-mcache
Включить инструкцию предзагрузки кэша.
-msecurity
Включить инструкции безопасности C-SKY.
-mtrust
Включить инструкции доверия C-SKY.
-mdsp
Включить инструкции DSP.
-medsp
Включить улучшенные инструкции DSP.
-mvdsp
Включить векторные инструкции DSP.
Следующие опции доступны, когда as настроен для процессора Epiphany.
-mepiphany
Указывает, что разрешены как 32-, так и 16-разрядные инструкции.
Это поведение по умолчанию.
-mepiphany16
Ограничивает разрешённые инструкции только 16-разрядным.
Следующие опции доступны, когда as настроен для процессора H8/300.
@chapter H8/300 Dependent Features
Options
Версия as для Renesas H8/300 имеет одну опцию, зависящую от машины:
-h-tick-hex
Поддерживать константы в стиле H'00 шестнадцатеричных чисел в дополнение к стилю 0x00.
-mach=name
Установить вариант машины H8300. Принимаемые имена машин: "h8300h", "h8300hn", "h8300s", "h8300sn", "h8300sx" и
"h8300sxn".
Следующие опции доступны, когда as настроен для процессора i386.
--32 | --x32 | --64
Выбрать размер слова, либо 32 бита, либо 64 бита. --32 подразумевает архитектуру Intel i386, в то время как --x32 и --64 подразумевают архитектуру AMD x86-64 с размером слова 32 бита или 64 бита соответственно.
Эти опции доступны только для формата объектного файла ELF и требуют, чтобы необходимая поддержка BFD была включена (на 32-разрядной платформе вам нужно добавить --enable-64-bit-bfd в configure для включения 64-разрядного использования и использовать x86-64 в качестве целевой платформы).
-n По умолчанию x86 GAS заменяет несколько инструкций nop, используемых для выравнивания внутри разделов кода, на многобайтовые инструкции nop, такие как leal 0(%esi,1),%esi. Эта опция отключает оптимизацию, если явно указан одиночный байт nop (0x90) в качестве заполнителя для выравнивания.
--divide
На платформах, производных от SVR4, символ / рассматривается как символ комментария, что означает, что он не может использоваться в выражениях. Опция --divide превращает / в нормальный символ. Это не отключает / в начале строки, начинающей комментарий, и не влияет на использование # для начала комментария.
-march=CPU[+EXTENSION...]
Эта опция указывает целевой процессор. Ассемблер выдаст сообщение об ошибке, если будет предпринята попытка собрать инструкцию, которая не выполнится на целевом процессоре. Принимаемые имена процессоров: "i8086", "i186", "i286",
"i386", "i486", "i586", "i686", "pentium", "pentiumpro",
"pentiumii", "pentiumiii", "pentium4", "prescott", "nocona",
"core", "core2", "corei7", "iamcu", "k6", "k6_2", "athlon",
"opteron", "k8", "amdfam10", "bdver1", "bdver2", "bdver3",
"bdver4", "znver1", "znver2", "znver3", "znver4", "znver5",
"btver1", "btver2", "generic32" и "generic64".
Помимо базового набора инструкций, ассемблеру можно указать принимать различные мнемоники расширений. Например,
"-march=i686+sse4+vmx" расширяет i686 с sse4 и vmx. В настоящее время поддерживаются следующие расширения: 8087, 287, 387, 687,
"cmov", "fxsr", "mmx", "sse", "sse2", "sse3", "sse4a", "ssse3",
"sse4.1", "sse4.2", "sse4", "avx", "avx2", "lahf_sahf", "monitor",
"adx", "rdseed", "prfchw", "smap", "mpx", "sha", "rdpid",
"ptwrite", "cet", "gfni", "vaes", "vpclmulqdq", "prefetchwt1",
"clflushopt", "se1", "clwb", "movdiri", "movdir64b", "enqcmd",
"serialize", "tsxldtrk", "kl", "widekl", "hreset", "avx512f",
"avx512cd", "avx512er", "avx512pf", "avx512vl", "avx512bw",
"avx512dq", "avx512ifma", "avx512vbmi", "avx512_4fmaps",
"avx512_4vnniw", "avx512_vpopcntdq", "avx512_vbmi2", "avx512_vnni",
"avx512_bitalg", "avx512_vp2intersect", "tdx", "avx512_bf16",
"avx_vnni", "avx512_fp16", "prefetchi", "avx_ifma",
"avx_vnni_int8", "cmpccxadd", "wrmsrns", "msrlist",
"avx_ne_convert", "rao_int", "fred", "lkgs", "avx_vnni_int16",
"sha512", "sm3", "sm4", "pbndkb", "avx10.1", "avx10.1/512",
"avx10.1/256", "avx10.1/128", "user_msr", "msr_imm", "apx_f",
"avx10.2", "avx10.2/512", "avx10.2/256", "avx10.2/128", "movrs",
"amx_int8", "amx_bf16", "amx_fp16", "amx_complex", "amx_transpose",
"amx_tf32", "amx_fp8" "amx_movrs", "amx_avx512", "amx_tile", "vmx",
"vmfunc", "smx", "xsave", "xsaveopt", "xsavec", "xsaves", "aes",
"pclmul", "fsgsbase", "rdrnd", "f16c", "bmi2", "fma", "movbe",
"ept", "lzcnt", "popcnt", "hle", "rtm", "tsx", "invpcid",
"clflush", "mwaitx", "clzero", "wbnoinvd", "pconfig", "waitpkg",
"uintr", "cldemote", "rdpru", "mcommit", "sev_es", "lwp", "fma4",
"xop", "cx16", "syscall", "rdtscp", "3dnow", "3dnowa", "sse4a",
"sse5", "snp", "invlpgb", "tlbsync", "svme", "gmism2", "gmiccs",
"padlockrng2", "padlockphe2" и "padlock". Обратите внимание, что эти мнемоники расширений можно предварять "no", чтобы отозвать соответствующую (и зависимую) функциональность. Обратите внимание также, что суффиксы, разрешённые на "-march=avx10.<N>", налагают ограничение на длину вектора, то есть, несмотря на то, что эти суффиксы в противном случае являются "включающими" опциями, использование этих суффиксов отключит все инструкции с операндами регистров векторов или масок шире.
Когда директива ".arch" используется с -march, директива ".arch" имеет преимущество.
-mtune=CPU
Эта опция указывает процессор для оптимизации. При использовании в сочетании с опцией -march будут генерироваться только инструкции процессора, указанного опцией -march.
Допустимые значения CPU идентичны списку процессоров для -march=CPU.
-moperand-check=none
-moperand-check=warning
-moperand-check=error
Эти опции управляют тем, должен ли ассемблер проверять определённые операнды инструкций или комбинации операндов. Пример - инструкции, где размер операнда не может быть выведен из его операндов и также не указан с помощью суффикса инструкции. -moperand-check=none заставит ассемблер не выполнять эти проверки. -moperand-check=warning заставит ассемблер выдавать предупреждение, когда соответствующие проверки не проходят, что является значением по умолчанию. -moperand-check=error заставит ассемблер выдавать ошибку, когда соответствующие проверки не проходят.
-msse2avx
Эта опция указывает, что ассемблер должен кодировать инструкции SSE с префиксом VEX, требуя наличия AVX. Инструкции SSE с расширенными GPR будут кодироваться с префиксом EVEX, требуя наличия AVX512 или AVX10.
-muse-unaligned-vector-move
Эта опция указывает, что ассемблер должен кодировать выровненные векторные перемещения как невыровненные векторные перемещения.
-msse-check=none
-msse-check=warning
-msse-check=error
Эти опции управляют тем, должен ли ассемблер проверять инструкции SSE. -msse-check=none заставит ассемблер не проверять инструкции SSE, что является значением по умолчанию. -msse-check=warning заставит ассемблер выдавать предупреждение для любой инструкции SSE. -msse-check=error заставит ассемблер выдавать ошибку для любой инструкции SSE.
-mavxscalar=128
-mavxscalar=256
Эти опции управляют тем, как ассемблер должен кодировать скалярные инструкции AVX. -mavxscalar=128 закодирует скалярные инструкции AVX с длиной вектора 128 бит, что является значением по умолчанию. -mavxscalar=256 закодирует скалярные инструкции AVX с длиной вектора 256 бит.
ПРЕДУПРЕЖДЕНИЕ: Не используйте это для производственного кода - из-за ошибок ЦП результирующий код может не работать на определённых моделях.
-mvexwig=0
-mvexwig=1
Эти опции управляют тем, как ассемблер должен кодировать игнорируемые VEX.W (WIG) инструкции VEX. -mvexwig=0 закодирует WIG инструкции VEX с vex.w = 0, что является значением по умолчанию. -mvexwig=1 закодирует WIG EVEX инструкции с vex.w = 1.
ПРЕДУПРЕЖДЕНИЕ: Не используйте это для производственного кода - из-за ошибок ЦП результирующий код может не работать на определённых моделях.
-mevexlig=128
-mevexlig=256
-mevexlig=512
Эти опции управляют тем, как ассемблер должен кодировать игнорируемые длины (LIG) инструкции EVEX. -mevexlig=128 закодирует LIG EVEX инструкции с длиной вектора 128 бит, что является значением по умолчанию.
-mevexlig=256 и -mevexlig=512 закодируют LIG EVEX инструкции с длиной вектора 256 бит и 512 бит соответственно.
-mevexwig=0
-mevexwig=1
Эти опции управляют тем, как ассемблер должен кодировать игнорируемые w (WIG) инструкции EVEX. -mevexwig=0 закодирует WIG EVEX инструкции с evex.w = 0, что является значением по умолчанию. -mevexwig=1 закодирует WIG EVEX инструкции с evex.w = 1.
-mmnemonic=att
-mmnemonic=intel
Эта опция указывает мнемонику инструкций для сопоставления инструкций. Директивы ".att_mnemonic" и ".intel_mnemonic" имеют преимущество.
-msyntax=att
-msyntax=intel
Эта опция указывает синтаксис инструкций при обработке инструкций. Директивы ".att_syntax" и ".intel_syntax" имеют преимущество.
-mnaked-reg
Эта опция указывает, что регистрам не требуется префикс %. Директивы ".att_syntax" и ".intel_syntax" имеют преимущество.
-madd-bnd-prefix
Эта опция заставляет ассемблер добавлять префикс BND ко всем ветвлениям, даже если такой префикс не был явно указан в исходном коде.
-mno-shared
На цели ELF ассемблер обычно оптимизирует ненужные релокации не-PLT против определённых не-слабых глобальных целей ветвления с видимостью по умолчанию. Опция -mshared говорит ассемблеру генерировать код, который может войти в разделяемую библиотеку, где все не-слабые глобальные цели ветвления с видимостью по умолчанию могут быть вытеснены.
Полученный код немного больше. Эта опция влияет только на обработку инструкций ветвления.
-mbig-obj
На цели PE/COFF эта опция заставляет использовать формат большого объектного файла, который позволяет более чем 32768 разделов.
-momit-lock-prefix=no
-momit-lock-prefix=yes
Эти опции управляют тем, как ассемблер должен кодировать префикс lock.
Эта опция предназначена как обходной путь для процессоров, которые сбоят на префиксе lock. Эта опция может быть безопасно использована только с однокристальными, однопоточными компьютерами -momit-lock-prefix=yes omitted all lock prefixes. -momit-lock-prefix=no encodes lock prefix as usual, which is the default.
-mfence-as-lock-add=no
-mfence-as-lock-add=yes
These options control how the assembler should encode lfence,
mfence and sfence. -mfence-as-lock-add=yes will encode lfence,
mfence and sfence as lock addl $0x0, (%rsp) in 64-bit mode and lock
addl $0x0, (%esp) in 32-bit mode. -mfence-as-lock-add=no will
encode lfence, mfence and sfence as usual, which is the default.
-mrelax-relocations=no
-mrelax-relocations=yes
These options control whether the assembler should generate relax
relocations, R_386_GOT32X, in 32-bit mode, or R_X86_64_GOTPCRELX
and R_X86_64_REX_GOTPCRELX, in 64-bit mode.
-mrelax-relocations=yes will generate relax relocations.
-mrelax-relocations=no will not generate relax relocations. The
default can be controlled by a configure option
--enable-x86-relax-relocations.
-mtls-check=no
-mtls-check=yes
These options control whether the assembler check tls relocation.
-mtls-check=yes will check tls relocation. -mtls-check=no will not
check tls relocation The default can be controlled by a configure
option --enable-x86-tls-check.
-malign-branch-boundary=NUM
This option controls how the assembler should align branches with
segment prefixes or NOP. NUM must be a power of 2. It should be 0
or no less than 16. Branches will be aligned within NUM byte
boundary. -malign-branch-boundary=0, which is the default, doesn't
align branches.
-malign-branch=TYPE[+TYPE...]
This option specifies types of branches to align. TYPE is
combination of jcc, which aligns conditional jumps, fused, which
aligns fused conditional jumps, jmp, which aligns unconditional
jumps, call which aligns calls, ret, which aligns rets, indirect,
which aligns indirect jumps and calls. The default is
-malign-branch=jcc+fused+jmp.
-malign-branch-prefix-size=NUM
This option specifies the maximum number of prefixes on an
instruction to align branches. NUM should be between 0 and 5. The
default NUM is 5.
-mbranches-within-32B-boundaries
This option aligns conditional jumps, fused conditional jumps and
unconditional jumps within 32 byte boundary with up to 5 segment
prefixes on an instruction. It is equivalent to
-malign-branch-boundary=32 -malign-branch=jcc+fused+jmp
-malign-branch-prefix-size=5. The default doesn't align branches.
-mlfence-after-load=no
-mlfence-after-load=yes
These options control whether the assembler should generate lfence
after load instructions. -mlfence-after-load=yes will generate
lfence. -mlfence-after-load=no will not generate lfence, which is
the default.
-mlfence-before-indirect-branch=none
-mlfence-before-indirect-branch=all
-mlfence-before-indirect-branch=register
-mlfence-before-indirect-branch=memory
These options control whether the assembler should generate lfence
before indirect near branch instructions.
-mlfence-before-indirect-branch=all will generate lfence before
indirect near branch via register and issue a warning before
indirect near branch via memory. It also implicitly sets
-mlfence-before-ret=shl when there's no explicit
-mlfence-before-ret=. -mlfence-before-indirect-branch=register
will generate lfence before indirect near branch via register.
-mlfence-before-indirect-branch=memory will issue a warning before
indirect near branch via memory.
-mlfence-before-indirect-branch=none will not generate lfence nor
issue warning, which is the default. Note that lfence won't be
generated before indirect near branch via register with
-mlfence-after-load=yes since lfence will be generated after
loading branch target register.
-mlfence-before-ret=none
-mlfence-before-ret=shl
-mlfence-before-ret=or
-mlfence-before-ret=yes
-mlfence-before-ret=not
These options control whether the assembler should generate lfence
before ret. -mlfence-before-ret=or will generate generate or
instruction with lfence. -mlfence-before-ret=shl/yes will generate
shl instruction with lfence. -mlfence-before-ret=not will generate
not instruction with lfence. -mlfence-before-ret=none will not
generate lfence, which is the default.
-mx86-used-note=no
-mx86-used-note=yes
These options control whether the assembler should generate
GNU_PROPERTY_X86_ISA_1_USED and GNU_PROPERTY_X86_FEATURE_2_USED GNU
property notes. The default can be controlled by the
--enable-x86-used-note configure option.
-mevexrcig=rne
-mevexrcig=rd
-mevexrcig=ru
-mevexrcig=rz
These options control how the assembler should encode SAE-only EVEX
instructions. -mevexrcig=rne will encode RC bits of EVEX
instruction with 00, which is the default. -mevexrcig=rd,
-mevexrcig=ru and -mevexrcig=rz will encode SAE-only EVEX
instructions with 01, 10 and 11 RC bits, respectively.
-mamd64
-mintel64
This option specifies that the assembler should accept only AMD64
or Intel64 ISA in 64-bit mode. The default is to accept common,
Intel64 only and AMD64 ISAs.
-O0 | -O | -O1 | -O2 | -Os
Optimize instruction encoding with smaller instruction size. -O
and -O1 encode 64-bit register load instructions with 64-bit
immediate as 32-bit register load instructions with 31-bit or
32-bits immediates, encode 64-bit register clearing instructions
with 32-bit register clearing instructions, encode 256-bit/512-bit
VEX/EVEX vector register clearing instructions with 128-bit VEX
vector register clearing instructions, encode 128-bit/256-bit EVEX
vector register load/store instructions with VEX vector register
load/store instructions, and encode 128-bit/256-bit EVEX packed
integer logical instructions with 128-bit/256-bit VEX packed
integer logical.
-O2 includes -O1 optimization plus encodes 256-bit/512-bit EVEX
vector register clearing instructions with 128-bit EVEX vector
register clearing instructions. In 64-bit mode VEX encoded
instructions with commutative source operands will also have their
source operands swapped if this allows using the 2-byte VEX prefix
form instead of the 3-byte one. Certain forms of AND as well as OR
with the same (register) operand specified twice will also be
changed to TEST.
-Os includes -O2 optimization plus encodes 16-bit, 32-bit and
64-bit register tests with immediate as 8-bit register test with
immediate. -O0 turns off this optimization.
Следующие опции доступны, когда as настроен для серии Ubicom IP2K.
-mip2022ext
Указывает, что разрешены расширенные инструкции IP2022.
-mip2022
Восстанавливает поведение по умолчанию, которое ограничивает разрешённые инструкции базовыми IP2022.
Следующие опции доступны, когда as настроен для процессоров Renesas M32C и M16C.
-m32c
Собрать инструкции M32C.
-m16c
Собрать инструкции M16C (значение по умолчанию).
-relax
Включить поддержку релаксаций во время связывания.
-h-tick-hex
Поддерживать константы в стиле H'00 шестнадцатеричных чисел в дополнение к стилю 0x00.
Следующие опции доступны, когда as настроен для серии Renesas M32R (ранее Mitsubishi M32R).
--m32rx
Указать, какой процессор в семье M32R является целью. Значение по умолчанию обычно M32R, но эта опция изменяет его на M32RX.
--warn-explicit-parallel-conflicts or --Wp
Выдавать сообщения предупреждений при обнаружении сомнительных параллельных конструкций.
--no-warn-explicit-parallel-conflicts or --Wnp
Не выдавать сообщения предупреждений при обнаружении сомнительных параллельных конструкций.
Следующие опции доступны, когда as настроен для серии Motorola 68000.
-l Сокращать ссылки на неопределённые символы до одного слова вместо двух.
-m68000 | -m68008 | -m68010 | -m68020 | -m68030
| -m68040 | -m68060 | -m68302 | -m68331 | -m68332
| -m68333 | -m68340 | -mcpu32 | -m5200
Указать, какой процессор в семье 68000 является целью. Значение по умолчанию обычно 68020, но это может быть изменено во время конфигурации.
-m68881 | -m68882 | -mno-68881 | -mno-68882
Целевая машина имеет (или не имеет) сопроцессор с плавающей точкой. Значение по умолчанию - предположить наличие сопроцессора для 68020,
68030 и cpu32. Хотя базовый 68000 не совместим с 68881, комбинацию из двух можно указать, поскольку возможно эмулирование инструкций сопроцессора с главным процессором.
-m68851 | -mno-68851
Целевая машина имеет (или не имеет) сопроцессор блока управления памятью. Значение по умолчанию - предположить наличие MMU для 68020 и выше.
Для деталей опций, зависящих от машины PDP-11, см. PDP-11-Options.
-mpic | -mno-pic
Генерировать позиционно-независимый (или позиционно-зависимый) код. Значение по умолчанию - -mpic.
-mall
-mall-extensions
Включить все расширения набора инструкций. Это значение по умолчанию.
-mno-extensions
Отключить все расширения набора инструкций.
-mextension | -mno-extension
Включить (или отключить) определённое расширение набора инструкций.
-mcpu
Включить расширения набора инструкций, поддерживаемые определённым CPU, и отключить все другие расширения.
-mmachine
Включить расширения набора инструкций, поддерживаемые определённой моделью машины, и отключить все другие расширения.
Следующие опции доступны, когда as настроен для процессора picoJava.
-mb Generate "big endian" format output.
-ml Generate "little endian" format output.
Следующие опции доступны, когда as настроен для процессора PRU.
-mlink-relax
Assume that LD would optimize LDI32 instructions by checking the
upper 16 bits of the expression. If they are all zeros, then LD
would shorten the LDI32 instruction to a single LDI. In such case
"as" will output DIFF relocations for diff expressions.
-mno-link-relax
Assume that LD would not optimize LDI32 instructions. As a
consequence, DIFF relocations will not be emitted.
-mno-warn-regname-label
Do not warn if a label name matches a register name. Usually
assembler programmers will want this warning to be emitted. C
compilers may want to turn this off.
Следующие опции доступны, когда as настроен для процессора MIPS.
-G num
Эта опция устанавливает наибольший размер объекта, на который можно ссылаться неявно с помощью регистра "gp". Она принимается только для целей, использующих формат ECOFF, таких как DECstation, работающий под Ultrix. Значение по умолчанию - 8.
-EB Generate "big endian" format output.
-EL Generate "little endian" format output.
-mips1
-mips2
-mips3
-mips4
-mips5
-mips32
-mips32r2
-mips32r3
-mips32r5
-mips32r6
-mips64
-mips64r2
-mips64r3
-mips64r5
-mips64r6
Generate code for a particular MIPS Instruction Set Architecture
level. -mips1 is an alias for -march=r3000, -mips2 is an alias for
-march=r6000, -mips3 is an alias for -march=r4000 and -mips4 is an
alias for -march=r8000. -mips5, -mips32, -mips32r2, -mips32r3,
-mips32r5, -mips32r6, -mips64, -mips64r2, -mips64r3, -mips64r5, and
-mips64r6 correspond to generic MIPS V, MIPS32, MIPS32 Release 2,
MIPS32 Release 3, MIPS32 Release 5, MIPS32 Release 6, MIPS64,
MIPS64 Release 2, MIPS64 Release 3, MIPS64 Release 5, and MIPS64
Release 6 ISA processors, respectively.
-march=cpu
Generate code for a particular MIPS CPU.
-mtune=cpu
Schedule and tune for a particular MIPS CPU.
-mfix7000
-mno-fix7000
Cause nops to be inserted if the read of the destination register
of an mfhi or mflo instruction occurs in the following two
instructions.
-mfix-rm7000
-mno-fix-rm7000
Cause nops to be inserted if a dmult or dmultu instruction is
followed by a load instruction.
-mfix-r5900
-mno-fix-r5900
Do not attempt to schedule the preceding instruction into the delay
slot of a branch instruction placed at the end of a short loop of
six instructions or fewer and always schedule a "nop" instruction
there instead. The short loop bug under certain conditions causes
loops to execute only once or twice, due to a hardware bug in the
R5900 chip.
-mdebug
-no-mdebug
Cause stabs-style debugging output to go into an ECOFF-style
.mdebug section instead of the standard ELF .stabs sections.
-mpdr
-mno-pdr
Control generation of ".pdr" sections.
-mgp32
-mfp32
The register sizes are normally inferred from the ISA and ABI, but
these flags force a certain group of registers to be treated as 32
bits wide at all times. -mgp32 controls the size of general-
purpose registers and -mfp32 controls the size of floating-point
registers.
-mgp64
-mfp64
The register sizes are normally inferred from the ISA and ABI, but
these flags force a certain group of registers to be treated as 64
bits wide at all times. -mgp64 controls the size of general-
purpose registers and -mfp64 controls the size of floating-point
registers.
-mfpxx
The register sizes are normally inferred from the ISA and ABI, but
using this flag in combination with -mabi=32 enables an ABI variant
which will operate correctly with floating-point registers which
are 32 or 64 bits wide.
-modd-spreg
-mno-odd-spreg
Enable use of floating-point operations on odd-numbered single-
precision registers when supported by the ISA. -mfpxx implies
-mno-odd-spreg, otherwise the default is -modd-spreg.
-mips16
-no-mips16
Generate code for the MIPS 16 processor. This is equivalent to
putting ".module mips16" at the start of the assembly file.
-no-mips16 turns off this option.
-mmips16e2
-mno-mips16e2
Enable the use of MIPS16e2 instructions in MIPS16 mode. This is
equivalent to putting ".module mips16e2" at the start of the
assembly file. -mno-mips16e2 turns off this option.
-mmicromips
-mno-micromips
Generate code for the microMIPS processor. This is equivalent to
putting ".module micromips" at the start of the assembly file.
-mno-micromips turns off this option. This is equivalent to
putting ".module nomicromips" at the start of the assembly file.
-msmartmips
-mno-smartmips
Enables the SmartMIPS extension to the MIPS32 instruction set.
This is equivalent to putting ".module smartmips" at the start of
the assembly file. -mno-smartmips turns off this option.
-mips3d
-no-mips3d
Generate code for the MIPS-3D Application Specific Extension. This
tells the assembler to accept MIPS-3D instructions. -no-mips3d
turns off this option.
-mdmx
-no-mdmx
Generate code for the MDMX Application Specific Extension. This
tells the assembler to accept MDMX instructions. -no-mdmx turns
off this option.
-mdsp
-mno-dsp
Generate code for the DSP Release 1 Application Specific Extension.
This tells the assembler to accept DSP Release 1 instructions.
-mno-dsp turns off this option.
-mdspr2
-mno-dspr2
Generate code for the DSP Release 2 Application Specific Extension.
This option implies -mdsp. This tells the assembler to accept DSP
Release 2 instructions. -mno-dspr2 turns off this option.
-mdspr3
-mno-dspr3
Generate code for the DSP Release 3 Application Specific Extension.
This option implies -mdsp and -mdspr2. This tells the assembler to
accept DSP Release 3 instructions. -mno-dspr3 turns off this
option.
-mmsa
-mno-msa
Generate code for the MIPS SIMD Architecture Extension. This tells
the assembler to accept MSA instructions. -mno-msa turns off this
option.
-mxpa
-mno-xpa
Generate code for the MIPS eXtended Physical Address (XPA)
Extension. This tells the assembler to accept XPA instructions.
-mno-xpa turns off this option.
-mmt
-mno-mt
Generate code for the MT Application Specific Extension. This
tells the assembler to accept MT instructions. -mno-mt turns off
this option.
-mmcu
-mno-mcu
Generate code for the MCU Application Specific Extension. This
tells the assembler to accept MCU instructions. -mno-mcu turns off
this option.
-mcrc
-mno-crc
Generate code for the MIPS cyclic redundancy check (CRC)
Application Specific Extension. This tells the assembler to accept
CRC instructions. -mno-crc turns off this option.
-mginv
-mno-ginv
Generate code for the Global INValidate (GINV) Application Specific
Extension. This tells the assembler to accept GINV instructions.
-mno-ginv turns off this option.
-mloongson-mmi
-mno-loongson-mmi
Generate code for the Loongson MultiMedia extensions Instructions
(MMI) Application Specific Extension. This tells the assembler to
accept MMI instructions. -mno-loongson-mmi turns off this option.
-mloongson-cam
-mno-loongson-cam
Generate code for the Loongson Content Address Memory (CAM)
instructions. This tells the assembler to accept Loongson CAM
instructions. -mno-loongson-cam turns off this option.
-mloongson-ext
-mno-loongson-ext
Generate code for the Loongson EXTensions (EXT) instructions. This
tells the assembler to accept Loongson EXT instructions.
-mno-loongson-ext turns off this option.
-mloongson-ext2
-mno-loongson-ext2
Generate code for the Loongson EXTensions R2 (EXT2) instructions.
This option implies -mloongson-ext. This tells the assembler to
accept Loongson EXT2 instructions. -mno-loongson-ext2 turns off
this option.
-minsn32
-mno-insn32
Only use 32-bit instruction encodings when generating code for the
microMIPS processor. This option inhibits the use of any 16-bit
instructions. This is equivalent to putting ".set insn32" at the
start of the assembly file. -mno-insn32 turns off this option.
This is equivalent to putting ".set noinsn32" at the start of the
assembly file. By default -mno-insn32 is selected, allowing all
instructions to be used.
--construct-floats
--no-construct-floats
The --no-construct-floats option disables the construction of
double width floating point constants by loading the two halves of
the value into the two single width floating point registers that
make up the double width register. By default --construct-floats
is selected, allowing construction of these floating point
constants.
--relax-branch
--no-relax-branch
The --relax-branch option enables the relaxation of out-of-range
branches. By default --no-relax-branch is selected, causing any
out-of-range branches to produce an error.
-mignore-branch-isa
-mno-ignore-branch-isa
Ignore branch checks for invalid transitions between ISA modes.
The semantics of branches does not provide for an ISA mode switch,
so in most cases the ISA mode a branch has been encoded for has to
be the same as the ISA mode of the branch's target label.
Therefore GAS has checks implemented that verify in branch assembly
that the two ISA modes match. -mignore-branch-isa disables these
checks. By default -mno-ignore-branch-isa is selected, causing any
invalid branch requiring a transition between ISA modes to produce
an error.
-mnan=encoding
Select between the IEEE 754-2008 (-mnan=2008) or the legacy
(-mnan=legacy) NaN encoding format. The latter is the default.
--emulation=name
This option was formerly used to switch between ELF and ECOFF
output on targets like IRIX 5 that supported both. MIPS ECOFF
support was removed in GAS 2.24, so the option now serves little
purpose. It is retained for backwards compatibility.
The available configuration names are: mipself, mipslelf and
mipsbelf. Choosing mipself now has no effect, since the output is
always ELF. mipslelf and mipsbelf select little- and big-endian
output respectively, but -EL and -EB are now the preferred options
instead.
-nocpp
as ignores this option. It is accepted for compatibility with the
native tools.
--trap
--no-trap
--break
--no-break
Control how to deal with multiplication overflow and division by
zero. --trap or --no-break (which are synonyms) take a trap
exception (and only work for Instruction Set Architecture level 2
and higher); --break or --no-trap (also synonyms, and the default)
take a break exception.
-n When this option is used, as will issue a warning every time it
generates a nop instruction from a macro.
Следующие опции доступны, когда as настроен для процессора LoongArch.
-fpic
-fPIC
Generate position-independent code
-fno-pic
Don't generate position-independent code (default)
Следующие опции доступны, когда as настроен для процессора Meta.
"-mcpu=metac11"
Generate code for Meta 1.1.
"-mcpu=metac12"
Generate code for Meta 1.2.
"-mcpu=metac21"
Generate code for Meta 2.1.
"-mfpu=metac21"
Allow code to use FPU hardware of Meta 2.1.
См. страницы info для документации по опциям, специфичным для MMIX.
Следующие опции доступны, когда as настроен для процессора NDS32.
"-O1"
Optimize for performance.
"-Os"
Optimize for space.
"-EL"
Produce little endian data output.
"-EB"
Produce little endian data output.
"-mpic"
Generate PIC.
"-mno-fp-as-gp-relax"
Suppress fp-as-gp relaxation for this file.
"-mb2bb-relax"
Back-to-back branch optimization.
"-mno-all-relax"
Suppress all relaxation for this file.
"-march=<arch name>"
Assemble for architecture <arch name> which could be v3, v3j, v3m,
v3f, v3s, v2, v2j, v2f, v2s.
"-mbaseline=<baseline>"
Assemble for baseline <baseline> which could be v2, v3, v3m.
"-mfpu-freg=FREG"
Specify a FPU configuration.
"0 8 SP / 4 DP registers"
"1 16 SP / 8 DP registers"
"2 32 SP / 16 DP registers"
"3 32 SP / 32 DP registers"
"-mabi=abi"
Specify a abi version <abi> could be v1, v2, v2fp, v2fpp.
"-m[no-]mac"
Enable/Disable Multiply instructions support.
"-m[no-]div"
Enable/Disable Divide instructions support.
"-m[no-]16bit-ext"
Enable/Disable 16-bit extension
"-m[no-]dx-regs"
Enable/Disable d0/d1 registers
"-m[no-]perf-ext"
Enable/Disable Performance extension
"-m[no-]perf2-ext"
Enable/Disable Performance extension 2
"-m[no-]string-ext"
Enable/Disable String extension
"-m[no-]reduced-regs"
Enable/Disable Reduced Register configuration (GPR16) option
"-m[no-]audio-isa-ext"
Enable/Disable AUDIO ISA extension
"-m[no-]fpu-sp-ext"
Enable/Disable FPU SP extension
"-m[no-]fpu-dp-ext"
Enable/Disable FPU DP extension
"-m[no-]fpu-fma"
Enable/Disable FPU fused-multiply-add instructions
"-mall-ext"
Turn on all extensions and instructions support
Следующие опции доступны, когда as настроен для процессора PowerPC.
-a32
Generate ELF32 or XCOFF32.
-a64
Generate ELF64 or XCOFF64.
-K PIC
Set EF_PPC_RELOCATABLE_LIB in ELF flags.
-mpwrx | -mpwr2
Generate code for POWER/2 (RIOS2).
-mpwr
Generate code for POWER (RIOS1)
-m601
Generate code for PowerPC 601.
-mppc, -mppc32, -m603, -m604
Generate code for PowerPC 603/604.
-m403, -m405
Generate code for PowerPC 403/405.
-m440
Generate code for PowerPC 440. BookE and some 405 instructions.
-m464
Generate code for PowerPC 464.
-m476
Generate code for PowerPC 476.
-m7400, -m7410, -m7450, -m7455
Generate code for PowerPC 7400/7410/7450/7455.
-m750cl, -mgekko, -mbroadway
Generate code for PowerPC 750CL/Gekko/Broadway.
-m821, -m850, -m860
Generate code for PowerPC 821/850/860.
-mppc64, -m620
Generate code for PowerPC 620/625/630.
-me200z2, -me200z4
Generate code for e200 variants, e200z2 with LSP, e200z4 with SPE.
-me300
Generate code for PowerPC e300 family.
-me500, -me500x2
Generate code for Motorola e500 core complex.
-me500mc
Generate code for Freescale e500mc core complex.
-me500mc64
Generate code for Freescale e500mc64 core complex.
-me5500
Generate code for Freescale e5500 core complex.
-me6500
Generate code for Freescale e6500 core complex.
-mlsp
Enable LSP instructions. (Disables SPE and SPE2.)
-mspe
Generate code for Motorola SPE instructions. (Disables LSP.)
-mspe2
Generate code for Freescale SPE2 instructions. (Disables LSP.)
-mtitan
Generate code for AppliedMicro Titan core complex.
-mppc64bridge
Generate code for PowerPC 64, including bridge insns.
-mbooke
Generate code for 32-bit BookE.
-ma2
Generate code for A2 architecture.
-maltivec
Generate code for processors with AltiVec instructions.
-mvle
Generate code for Freescale PowerPC VLE instructions.
-mvsx
Generate code for processors with Vector-Scalar (VSX) instructions.
-mhtm
Generate code for processors with Hardware Transactional Memory
instructions.
-mpower4, -mpwr4
Generate code for Power4 architecture.
-mpower5, -mpwr5, -mpwr5x
Generate code for Power5 architecture.
-mpower6, -mpwr6
Generate code for Power6 architecture.
-mpower7, -mpwr7
Generate code for Power7 architecture.
-mpower8, -mpwr8
Generate code for Power8 architecture.
-mpower9, -mpwr9
Generate code for Power9 architecture.
-mpower10, -mpwr10
Generate code for Power10 architecture.
-mpower11, -mpwr11
Generate code for Power11 architecture.
-mfuture
Generate code for 'future' architecture.
-mcell
-mcell
Generate code for Cell Broadband Engine architecture.
-mcom
Generate code Power/PowerPC common instructions.
-many
Generate code for any architecture (PWR/PWRX/PPC).
-mregnames
Allow symbolic names for registers.
-mno-regnames
Do not allow symbolic names for registers.
-mrelocatable
Support for GCC's -mrelocatable option.
-mrelocatable-lib
Support for GCC's -mrelocatable-lib option.
-memb
Set PPC_EMB bit in ELF flags.
-mlittle, -mlittle-endian, -le
Generate code for a little endian machine.
-mbig, -mbig-endian, -be
Generate code for a big endian machine.
-msolaris
Generate code for Solaris.
-mno-solaris
Do not generate code for Solaris.
-nops=count
If an alignment directive inserts more than count nops, put a
branch at the beginning to skip execution of the nops.
Следующие опции доступны, когда as настроен для процессора RISC-V.
-fpic
-fPIC
Generate position-independent code
-fno-pic
Don't generate position-independent code (default)
-march=ISA
Select the base isa, as specified by ISA. For example
-march=rv32ima. If this option and the architecture attributes
aren't set, then assembler will check the default configure setting
--with-arch=ISA.
-misa-spec=ISAspec
Select the default isa spec version. If the version of ISA isn't
set by -march, then assembler helps to set the version according to
the default chosen spec. If this option isn't set, then assembler
will check the default configure setting --with-isa-spec=ISAspec.
-mpriv-spec=PRIVspec
Select the privileged spec version. We can decide whether the CSR
is valid or not according to the chosen spec. If this option and
the privilege attributes aren't set, then assembler will check the
default configure setting --with-priv-spec=PRIVspec.
-mabi=ABI
Selects the ABI, which is either "ilp32" or "lp64", optionally
followed by "f", "d", or "q" to indicate single-precision, double-
precision, or quad-precision floating-point calling convention, or
none or "e" to indicate the soft-float calling convention ("e"
indicates a soft-float RVE ABI).
-mrelax
Take advantage of linker relaxations to reduce the number of
instructions required to materialize symbol addresses. (default)
-mno-relax
Don't do linker relaxations.
-march-attr
Generate the default contents for the riscv elf attribute section
if the .attribute directives are not set. This section is used to
record the information that a linker or runtime loader needs to
check compatibility. This information includes ISA string, stack
alignment requirement, unaligned memory accesses, and the major,
minor and revision version of privileged specification.
-mno-arch-attr
Don't generate the default riscv elf attribute section if the
.attribute directives are not set.
-mcsr-check
Enable the CSR checking for the ISA-dependent CRS and the read-only
CSR. The ISA-dependent CSR are only valid when the specific ISA is
set. The read-only CSR can not be written by the CSR instructions.
-mno-csr-check
Don't do CSR checking.
-mlittle-endian
Generate code for a little endian machine.
-mbig-endian
Generate code for a big endian machine.
См. страницы info для документации по опциям, специфичным для RX.
Следующие опции доступны, когда as настроен для семейства процессоров s390.
-m31
-m64
Select the word size, either 31/32 bits or 64 bits.
-mesa
-mzarch
Select the architecture mode, either the Enterprise System
Architecture (esa) or the z/Architecture mode (zarch).
-march=processor
Specify which s390 processor variant is the target, g5 (or arch3),
g6, z900 (or arch5), z990 (or arch6), z9-109, z9-ec (or arch7), z10
(or arch8), z196 (or arch9), zEC12 (or arch10), z13 (or arch11),
z14 (or arch12), z15 (or arch13), z16 (or arch14), or arch15.
-mregnames
-mno-regnames
Allow or disallow symbolic names for registers.
-mwarn-areg-zero
Warn whenever the operand for a base or index register has been
specified but evaluates to zero.
-mwarn-regtype-mismatch=strict
-mwarn-regtype-mismatch=relaxed
-mwarn-regtype-mismatch=no
-mno-warn-regtype-mismatch
Controls whether the assembler performs register name type checks
and generates a warning message in case of a mismatch with the
operand register type. The default (which can be restored by using
the relaxed argument) is to perform relaxed register name type
checks, which allow floating point register (FPR) names %f0 to %f15
to be specified as argument to vector register (VR) operands and
vector register (VR) names %v0 to %v15 to be specified as argument
to floating point register (FPR) operands. This is acceptable as
the FPR are embedded into the lower half of the VR. Using the
strict argument strict register name type checks are performed.
The no argument, which is equivalent to -mno-warn-regtype-mismatch,
disables any register name type checks.
Следующие опции доступны, когда as настроен для процессора TMS320C6000.
-march=arch
Enable (only) instructions from architecture arch. By default, all
instructions are permitted.
The following values of arch are accepted: "c62x", "c64x", "c64x+",
"c67x", "c67x+", "c674x".
-mdsbt
-mno-dsbt
The -mdsbt option causes the assembler to generate the
"Tag_ABI_DSBT" attribute with a value of 1, indicating that the
code is using DSBT addressing. The -mno-dsbt option, the default,
causes the tag to have a value of 0, indicating that the code does
not use DSBT addressing. The linker will emit a warning if objects
of different type (DSBT and non-DSBT) are linked together.
-mpid=no
-mpid=near
-mpid=far
The -mpid= option causes the assembler to generate the
"Tag_ABI_PID" attribute with a value indicating the form of data
addressing used by the code. -mpid=no, the default, indicates
position-dependent data addressing, -mpid=near indicates position-
independent addressing with GOT accesses using near DP addressing,
and -mpid=far indicates position-independent addressing with GOT
accesses using far DP addressing. The linker will emit a warning
if objects built with different settings of this option are linked
together.
-mpic
-mno-pic
The -mpic option causes the assembler to generate the "Tag_ABI_PIC"
attribute with a value of 1, indicating that the code is using
position-independent code addressing, The "-mno-pic" option, the
default, causes the tag to have a value of 0, indicating position-
dependent code addressing. The linker will emit a warning if
objects of different type (position-dependent and position-
independent) are linked together.
-mbig-endian
-mlittle-endian
Generate code for the specified endianness. The default is little-
endian.
Следующие опции доступны, когда as настроен для процессора TILE-Gx.
-m32 | -m64
Select the word size, either 32 bits or 64 bits.
-EB | -EL
Select the endianness, either big-endian (-EB) or little-endian
(-EL).
Следующая опция доступна, когда as настроен для процессора Visium.
-mtune=arch
This option specifies the target architecture. If an attempt is
made to assemble an instruction that will not execute on the target
architecture, the assembler will issue an error message.
The following names are recognized: "mcm24" "mcm" "gr5" "gr6"
Следующие опции доступны, когда as настроен для процессора Xtensa.
--text-section-literals | --no-text-section-literals
Control the treatment of literal pools. The default is
--no-text-section-literals, which places literals in separate
sections in the output file. This allows the literal pool to be
placed in a data RAM/ROM. With --text-section-literals, the
literals are interspersed in the text section in order to keep them
as close as possible to their references. This may be necessary
for large assembly files, where the literals would otherwise be out
of range of the "L32R" instructions in the text section. Literals
are grouped into pools following ".literal_position" directives or
preceding "ENTRY" instructions. These options only affect literals
referenced via PC-relative "L32R" instructions; literals for
absolute mode "L32R" instructions are handled separately.
--auto-litpools | --no-auto-litpools
Control the treatment of literal pools. The default is
--no-auto-litpools, which in the absence of --text-section-literals
places literals in separate sections in the output file. This
allows the literal pool to be placed in a data RAM/ROM. With
--auto-litpools, the literals are interspersed in the text section
in order to keep them as close as possible to their references,
explicit ".literal_position" directives are not required. This may
be necessary for very large functions, where single literal pool at
the beginning of the function may not be reachable by "L32R"
instructions at the end. These options only affect literals
referenced via PC-relative "L32R" instructions; literals for
absolute mode "L32R" instructions are handled separately. When
used together with --text-section-literals, --auto-litpools takes
precedence.
--absolute-literals | --no-absolute-literals
Indicate to the assembler whether "L32R" instructions use absolute
or PC-relative addressing. If the processor includes the absolute
addressing option, the default is to use absolute "L32R"
relocations. Otherwise, only the PC-relative "L32R" relocations
can be used.
--target-align | --no-target-align
Enable or disable automatic alignment to reduce branch penalties at
some expense in code size. This optimization is enabled by
default. Note that the assembler will always align instructions
like "LOOP" that have fixed alignment requirements.
--longcalls | --no-longcalls
Enable or disable transformation of call instructions to allow
calls across a greater range of addresses. This option should be
used when call targets can potentially be out of range. It may
degrade both code size and performance, but the linker can
generally optimize away the unnecessary overhead when a call ends
up within range. The default is --no-longcalls.
--transform | --no-transform
Enable or disable all assembler transformations of Xtensa
instructions, including both relaxation and optimization. The
default is --transform; --no-transform should only be used in the
rare cases when the instructions must be exactly as specified in
the assembly source. Using --no-transform causes out of range
instruction operands to be errors.
--rename-section oldname=newname
Rename the oldname section to newname. This option can be used
multiple times to rename multiple sections.
--trampolines | --no-trampolines
Enable or disable transformation of jump instructions to allow
jumps across a greater range of addresses. This option should be
used when jump targets can potentially be out of range. In the
absence of such jumps this option does not affect code size or
performance. The default is --trampolines.
--abi-windowed | --abi-call0
Choose ABI tag written to the ".xtensa.info" section. ABI tag
indicates ABI of the assembly code. A warning is issued by the
linker on an attempt to link object files with inconsistent ABI
tags. Default ABI is chosen by the Xtensa core configuration.
Следующие опции доступны, когда as настроен для процессора Z80.
@chapter Z80 Dependent Features
Command-line Options
-march=CPU[-EXT...][+EXT...]
This option specifies the target processor. The assembler will
issue an error message if an attempt is made to assemble an
instruction which will not execute on the target processor. The
following processor names are recognized: "z80", "z180", "ez80",
"gbz80", "z80n", "r800". In addition to the basic instruction set,
the assembler can be told to accept some extension mnemonics. For
example, "-march=z180+sli+infc" extends z180 with SLI instructions
and IN F,(C). The following extensions are currently supported:
"full" (all known instructions), "adl" (ADL CPU mode by default,
eZ80 only), "sli" (instruction known as SLI, SLL or SL1), "xyhl"
(instructions with halves of index registers: IXL, IXH, IYL, IYH),
"xdcb" (instructions like RotOp (II+d),R and BitOp n,(II+d),R),
"infc" (instruction IN F,(C) or IN (C)), "outc0" (instruction OUT
(C),0). Note that rather than extending a basic instruction set,
the extension mnemonics starting with "-" revoke the respective
functionality: "-march=z80-full+xyhl" first removes all default
extensions and adds support for index registers halves only.
If this option is not specified then "-march=z80+xyhl+infc" is
assumed.
-local-prefix=prefix
Mark all labels with specified prefix as local. But such label can
be marked global explicitly in the code. This option do not change
default local label prefix ".L", it is just adds new one.
-colonless
Accept colonless labels. All symbols at line begin are treated as
labels.
-sdcc
Accept assembler code produced by SDCC.
-fp-s=FORMAT
Single precision floating point numbers format. Default: ieee754
(32 bit).
-fp-d=FORMAT
Double precision floating point numbers format. Default: ieee754
(64 bit).
SEE ALSO
gcc(1), ld(1), и записи Info для binutils и ld.
COPYRIGHT
Copyright (c) 1991-2025 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3 or
any later version published by the Free Software Foundation; with no
Invariant Sections, with no Front-Cover Texts, and with no Back-Cover
Texts. A copy of the license is included in the section entitled "GNU
Free Documentation License".
binutils-2.44 2025-05-12 AS(1)
AS(1) GNU Development Tools AS(1)
NAME
AS - the portable GNU assembler.
SYNOPSIS
as [-a[cdghilns][=file]]
[--alternate]
[--compress-debug-sections] [--nocompress-debug-sections]
[-D]
[--dump-config]
[--debug-prefix-map old=new]
[--defsym sym=val]
[--elf-stt-common=[no|yes]]
[--emulation=name]
[-f]
[-g] [--gstabs] [--gstabs+]
[--gdwarf-<N>] [--gdwarf-sections]
[--gdwarf-cie-version=VERSION]
[--generate-missing-build-notes=[no|yes]]
[--gsframe]
[--hash-size=N]
[--help] [--target-help]
[--info] [--no-info]
[-I dir]
[-J]
[-K]
[--keep-locals]
[-L]
[--listing-lhs-width=NUM]
[--listing-lhs-width2=NUM]
[--listing-rhs-width=NUM]
[--listing-cont-lines=NUM]
[--multibyte-handling=[allow|warn|warn-sym-only]]
[--no-pad-sections]
[-o objfile] [-R]
[--scfi=experimental]
[--sectname-subst]
[--size-check=[error|warning]]
[--statistics]
[-v] [-version] [--version]
[-W] [--no-warn] [--warn] [--fatal-warnings]
[-w] [-x]
[-Z] [@FILE]
[target-options]
[--|files ...]
TARGET
Target AArch64 options:
[-EB|-EL]
[-mabi=ABI]
Target Alpha options:
[-mcpu]
[-mdebug | -no-mdebug]
[-replace | -noreplace]
[-relax] [-g] [-Gsize]
[-F] [-32addr]
Target ARC options:
[-mcpu=cpu]
[-mA6|-mARC600|-mARC601|-mA7|-mARC700|-mEM|-mHS]
[-mcode-density]
[-mrelax]
[-EB|-EL]
Target ARM options:
[-mcpu=processor[+extension...]]
[-march=architecture[+extension...]]
[-mfpu=floating-point-format]
[-mfloat-abi=abi]
[-meabi=ver]
[-mthumb]
[-EB|-EL]
[-mapcs-32|-mapcs-26|-mapcs-float|
-mapcs-reentrant]
[-mthumb-interwork] [-k]
Target Blackfin options:
[-mcpu=processor[-sirevision]]
[-mfdpic]
[-mno-fdpic]
[-mnopic]
Target BPF options:
[-EL] [-EB]
Target CRIS options:
[--underscore | --no-underscore]
[--pic] [-N]
[--emulation=criself | --emulation=crisaout]
[--march=v0_v10 | --march=v10 | --march=v32 |
--march=common_v10_v32]
Target C-SKY options:
[-march=arch] [-mcpu=cpu]
[-EL] [-mlittle-endian] [-EB] [-mbig-endian]
[-fpic] [-pic]
[-mljump] [-mno-ljump]
[-force2bsr] [-mforce2bsr] [-no-force2bsr] [-mno-force2bsr]
[-jsri2bsr] [-mjsri2bsr] [-no-jsri2bsr ] [-mno-jsri2bsr]
[-mnolrw ] [-mno-lrw]
[-melrw] [-mno-elrw]
[-mlaf ] [-mliterals-after-func]
[-mno-laf] [-mno-literals-after-func]
[-mlabr] [-mliterals-after-br]
[-mno-labr] [-mnoliterals-after-br]
[-mistack] [-mno-istack]
[-mhard-float] [-mmp] [-mcp] [-mcache]
[-msecurity] [-mtrust]
[-mdsp] [-medsp] [-mvdsp]
Target D10V options:
[-O]
Target D30V options:
[-O|-n|-N]
Target EPIPHANY options:
[-mepiphany|-mepiphany16]
Target H8/300 options:
[-h-tick-hex]
Target i386 options:
[--32|--x32|--64] [-n]
[-march=CPU[+EXTENSION...]] [-mtune=CPU]
Target IA-64 options:
[-mconstant-gp|-mauto-pic]
[-milp32|-milp64|-mlp64|-mp64]
[-mle|mbe]
[-mtune=itanium1|-mtune=itanium2]
[-munwind-check=warning|-munwind-check=error]
[-mhint.b=ok|-mhint.b=warning|-mhint.b=error]
[-x|-xexplicit] [-xauto] [-xdebug]
Target IP2K options:
[-mip2022|-mip2022ext]
Target M32C options:
[-m32c|-m16c] [-relax] [-h-tick-hex]
Target M32R options:
[--m32rx|--[no-]warn-explicit-parallel-conflicts|
--W[n]p]
Target M680X0 options:
[-l] [-m68000|-m68010|-m68020|...]
Target M68HC11 options:
[-m68hc11|-m68hc12|-m68hcs12|-mm9s12x|-mm9s12xg]
[-mshort|-mlong]
[-mshort-double|-mlong-double]
[--force-long-branches] [--short-branches]
[--strict-direct-mode] [--print-insn-syntax]
[--print-opcodes] [--generate-example]
Target MCORE options:
[-jsri2bsr] [-sifilter] [-relax]
[-mcpu=[210|340]]
Target Meta options:
[-mcpu=cpu] [-mfpu=cpu] [-mdsp=cpu] Target MICROBLAZE options:
[-mlittle-endian] [-mbig-endian]
Target MIPS options:
[-nocpp] [-EL] [-EB] [-O[optimization level]]
[-g[debug level]] [-G num] [-KPIC] [-call_shared]
[-non_shared] [-xgot [-mvxworks-pic]
[-mabi=ABI] [-32] [-n32] [-64] [-mfp32] [-mgp32]
[-mfp64] [-mgp64] [-mfpxx]
[-modd-spreg] [-mno-odd-spreg]
[-march=CPU] [-mtune=CPU] [-mips1] [-mips2]
[-mips3] [-mips4] [-mips5] [-mips32] [-mips32r2]
[-mips32r3] [-mips32r5] [-mips32r6] [-mips64] [-mips64r2]
[-mips64r3] [-mips64r5] [-mips64r6]
[-construct-floats] [-no-construct-floats]
[-mignore-branch-isa] [-mno-ignore-branch-isa]
[-mnan=encoding]
[-trap] [-no-break] [-break] [-no-trap]
[-mips16] [-no-mips16]
[-mmips16e2] [-mno-mips16e2]
[-mmicromips] [-mno-micromips]
[-msmartmips] [-mno-smartmips]
[-mips3d] [-no-mips3d]
[-mdmx] [-no-mdmx]
[-mdsp] [-mno-dsp]
[-mdspr2] [-mno-dspr2]
[-mdspr3] [-mno-dspr3]
[-mmsa] [-mno-msa]
[-mxpa] [-mno-xpa]
[-mmt] [-mno-mt]
[-mmcu] [-mno-mcu]
[-mcrc] [-mno-crc]
[-mginv] [-mno-ginv]
[-mloongson-mmi] [-mno-loongson-mmi]
[-mloongson-cam] [-mno-loongson-cam]
[-mloongson-ext] [-mno-loongson-ext]
[-mloongson-ext2] [-mno-loongson-ext2]
[-minsn32] [-mno-insn32]
[-mfix7000] [-mno-fix7000]
[-mfix-rm7000] [-mno-fix-rm7000]
[-mfix-vr4120] [-mno-fix-vr4120]
[-mfix-vr4130] [-mno-fix-vr4130]
[-mfix-r5900] [-mno-fix-r5900]
[-mdebug] [-no-mdebug]
[-mpdr] [-mno-pdr]
Target MMIX options:
[--fixed-special-register-names] [--globalize-symbols]
[--gnu-syntax] [--relax] [--no-predefined-symbols]
[--no-expand] [--no-merge-gregs] [-x]
[--linker-allocated-gregs]
Target NDS32 options:
[-EL] [-EB] [-O] [-Os] [-mcpu=cpu]
[-misa=isa] [-mabi=abi] [-mall-ext]
[-m[no-]16-bit] [-m[no-]perf-ext] [-m[no-]perf2-ext]
[-m[no-]string-ext] [-m[no-]dsp-ext] [-m[no-]mac] [-m[no-]div]
[-m[no-]audio-isa-ext] [-m[no-]fpu-sp-ext] [-m[no-]fpu-dp-ext]
[-m[no-]fpu-fma] [-mfpu-freg=FREG] [-mreduced-regs]
[-mfull-regs] [-m[no-]dx-regs] [-mpic] [-mno-relax]
[-mb2bb]
Target PDP11 options:
[-mpic|-mno-pic] [-mall] [-mno-extensions]
[-mextension|-mno-extension]
[-mcpu] [-mmachine]
Target picoJava options:
[-mb|-me]
Target PowerPC options:
[-a32|-a64]
[-mpwrx|-mpwr2|-mpwr|-m601|-mppc|-mppc32|-m603|-m604|-m403|-m405|
-m440|-m464|-m476|-m7400|-m7410|-m7450|-m7455|-m750cl|-mgekko|
-mbroadway|-mppc64|-m620|-me500|-e500x2|-me500mc|-me500mc64|-me5500|
-me6500|-mppc64bridge|-mbooke|-mpower4|-mpwr4|-mpower5|-mpwr5|-mpwr5x|
-mpower6|-mpwr6|-mpower7|-mpwr7|-mpower8|-mpwr8|-mpower9|-mpwr9-ma2|
-mcell|-mspe|-mspe2|-mtitan|-me300|-mcom]
[-many] [-maltivec|-mvsx|-mhtm|-mvle]
[-mregnames|-mno-regnames]
[-mrelocatable|-mrelocatable-lib|-K PIC] [-memb]
[-mlittle|-mlittle-endian|-le|-mbig|-mbig-endian|-be]
[-msolaris|-mno-solaris]
[-nops=count]
Target PRU options:
[-link-relax]
[-mnolink-relax]
[-mno-warn-regname-label]
Target RISC-V options:
[-fpic|-fPIC|-fno-pic]
[-march=ISA]
[-mabi=ABI]
[-mlittle-endian|-mbig-endian]
Target RL78 options:
[-mg10]
[-m32bit-doubles|-m64bit-doubles]
Target RX options:
[-mlittle-endian|-mbig-endian]
[-m32bit-doubles|-m64bit-doubles]
[-muse-conventional-section-names]
[-msmall-data-limit]
[-mpid]
[-mrelax]
[-mint-register=number]
[-mgcc-abi|-mrx-abi]
Target s390 options:
[-m31|-m64] [-mesa|-mzarch] [-march=CPU]
[-mregnames|-mno-regnames]
[-mwarn-areg-zero]
[-mwarn-regtype-mismatch=strict
-mwarn-regtype-mismatch=relaxed
-mwarn-regtype-mismatch=no
-mno-warn-regtype-mismatch]
Target SCORE options:
[-EB][-EL][-FIXDD][-NWARN]
[-SCORE5][-SCORE5U][-SCORE7][-SCORE3]
[-march=score7][-march=score3]
[-USE_R1][-KPIC][-O0][-G num][-V]
Target SPARC options:
[-Av6|-Av7|-Av8|-Aleon|-Asparclet|-Asparclite
-Av8plus|-Av8plusa|-Av8plusb|-Av8plusc|-Av8plusd
-Av8plusv|-Av8plusm|-Av9|-Av9a|-Av9b|-Av9c
-Av9d|-Av9e|-Av9v|-Av9m|-Asparc|-Asparcvis
-Asparcvis2|-Asparcfmaf|-Asparcima|-Asparcvis3
-Asparcvisr|-Asparc5]
[-xarch=v8plus|-xarch=v8plusa]|-xarch=v8plusb|-xarch=v8plusc
-xarch=v8plusd|-xarch=v8plusv|-xarch=v8plusm|-xarch=v9
-xarch=v9a|-xarch=v9b|-xarch=v9c|-xarch=v9d|-xarch=v9e
-xarch=v9v|-xarch=v9m|-xarch=sparc|-xarch=sparcvis
-xarch=sparcvis2|-xarch=sparcfmaf|-xarch=sparcima
-xarch=sparcvis3|-xarch=sparcvisr|-xarch=sparc5
-bump]
[-32|-64]
[--enforce-aligned-data][--dcti-couples-detect]
Target TIC54X options:
[-mcpu=54[123589]|-mcpu=54[56]lp] [-mfar-mode|-mf]
[-merrors-to-file <filename>|-me <filename>]
Target TIC6X options:
[-march=arch] [-mbig-endian|-mlittle-endian]
[-mdsbt|-mno-dsbt] [-mpid=no|-mpid=near|-mpid=far]
[-mpic|-mno-pic]
Target TILE-Gx options:
[-m32|-m64][-EB][-EL]
Target Visium options:
[-mtune=arch]
Target Xtensa options:
[--[no-]text-section-literals] [--[no-]auto-litpools]
[--[no-]absolute-literals]
[--[no-]target-align] [--[no-]longcalls]
[--[no-]transform]
[--rename-section oldname=newname]
[--[no-]trampolines]
[--abi-windowed|--abi-call0]
Target Z80 options:
[-march=CPU[-EXT][+EXT]]
[-local-prefix=PREFIX]
[-colonless]
[-sdcc]
[-fp-s=FORMAT]
[-fp-d=FORMAT]
DESCRIPTION
GNU as is really a family of assemblers. If you use (or have used) the
GNU assembler on one architecture, you should find a fairly similar
environment when you use it on another architecture. Each version has
much in common with the others, including object file formats, most
assembler directives (often called pseudo-ops) and assembler syntax.
as is primarily intended to assemble the output of the GNU C compiler
"gcc" for use by the linker "ld". Nevertheless, we've tried to make as
assemble correctly everything that other assemblers for the same
machine would assemble. Any exceptions are documented explicitly.
This doesn't mean as always uses the same syntax as another assembler
for the same architecture; for example, we know of several incompatible
versions of 680x0 assembly language syntax.
Each time you run as it assembles exactly one source program. The
source program is made up of one or more files. (The standard input is
also a file.)
You give as a command line that has zero or more input file names. The
input files are read (from left file name to right). A command-line
argument (in any position) that has no special meaning is taken to be
an input file name.
If you give as no file names it attempts to read one input file from
the as standard input, which is normally your terminal. You may have
to type ctl-D to tell as there is no more program to assemble.
Use -- if you need to explicitly name the standard input file in your
command line.
If the source is empty, as produces a small, empty object file.
as may write warnings and error messages to the standard error file
(usually your terminal). This should not happen when a compiler runs
as automatically. Warnings report an assumption made so that as could
keep assembling a flawed program; errors report a grave problem that
stops the assembly.
If you are invoking as via the GNU C compiler, you can use the -Wa
option to pass arguments through to the assembler. The assembler
arguments must be separated from each other (and the -Wa) by commas.
For example:
gcc -c -g -O -Wa,-alh,-L file.c
This passes two options to the assembler: -alh (emit a listing to
standard output with high-level and assembly source) and -L (retain
local symbols in the symbol table).
Usually you do not need to use this -Wa mechanism, since many compiler
command-line options are automatically passed to the assembler by the
compiler. (You can call the GNU compiler driver with the -v option to
see precisely what options it passes to each compilation pass,
including the assembler.)
OPTIONS
@file
Read command-line options from file. The options read are inserted
in place of the original @file option. If file does not exist, or
cannot be read, then the option will be treated literally, and not
removed.
Options in file are separated by whitespace. A whitespace
character may be included in an option by surrounding the entire
option in either single or double quotes. Any character (including
a backslash) may be included by prefixing the character to be
included with a backslash. The file may itself contain additional
@file options; any such options will be processed recursively.
-a[cdghilmns]
Turn on listings, in any of a variety of ways:
-ac omit false conditionals
-ad omit debugging directives
-ag include general information, like as version and options passed
-ah include high-level source
-al include assembly
-ali
include assembly with ginsn
-am include macro expansions
-an omit forms processing
-as include symbols
=file
set the name of the listing file
You may combine these options; for example, use -aln for assembly
listing without forms processing. The =file option, if used, must
be the last one. By itself, -a defaults to -ahls.
--alternate
Begin in alternate macro mode.
--compress-debug-sections
Compress DWARF debug sections using zlib with SHF_COMPRESSED from
the ELF ABI. The resulting object file may not be compatible with
older linkers and object file utilities. Note if compression would
make a given section larger then it is not compressed.
--compress-debug-sections=none
--compress-debug-sections=zlib
--compress-debug-sections=zlib-gnu
--compress-debug-sections=zlib-gabi
--compress-debug-sections=zstd
These options control how DWARF debug sections are compressed.
--compress-debug-sections=none is equivalent to
--nocompress-debug-sections. --compress-debug-sections=zlib and
--compress-debug-sections=zlib-gabi are equivalent to
--compress-debug-sections. --compress-debug-sections=zlib-gnu
compresses DWARF debug sections using the obsoleted zlib-gnu
format. The debug sections are renamed to begin with .zdebug.
--compress-debug-sections=zstd compresses DWARF debug sections
using zstd. Note - if compression would actually make a section
larger, then it is not compressed nor renamed.
--nocompress-debug-sections
Do not compress DWARF debug sections. This is usually the default
for all targets except the x86/x86_64, but a configure time option
can be used to override this.
-D Enable debugging in target specific backends, if supported.
Otherwise ignored. Even if ignored, this option is accepted for
script compatibility with calls to other assemblers.
--debug-prefix-map old=new
When assembling files in directory old, record debugging
information describing them as in new instead.
--defsym sym=value
Define the symbol sym to be value before assembling the input file.
value must be an integer constant. As in C, a leading 0x indicates
a hexadecimal value, and a leading 0 indicates an octal value. The
value of the symbol can be overridden inside a source file via the
use of a ".set" pseudo-op.
--dump-config
Displays how the assembler is configured and then exits.
--elf-stt-common=no
--elf-stt-common=yes
These options control whether the ELF assembler should generate
common symbols with the "STT_COMMON" type. The default can be
controlled by a configure option --enable-elf-stt-common.
--emulation=name
If the assembler is configured to support multiple different target
configurations then this option can be used to select the desired
form.
-f "fast"---skip whitespace and comment preprocessing (assume source
is compiler output).
-g
--gen-debug
Generate debugging information for each assembler source line using
whichever debug format is preferred by the target. This currently
means either STABS, ECOFF or DWARF2. When the debug format is
DWARF then a ".debug_info" and ".debug_line" section is only
emitted when the assembly file doesn't generate one itself.
--gstabs
Generate stabs debugging information for each assembler line. This
may help debugging assembler code, if the debugger can handle it.
--gstabs+
Generate stabs debugging information for each assembler line, with
GNU extensions that probably only gdb can handle, and that could
make other debuggers crash or refuse to read your program. This
may help debugging assembler code. Currently the only GNU
extension is the location of the current working directory at
assembling time.
--gdwarf-2
Generate DWARF2 debugging information for each assembler line.
This may help debugging assembler code, if the debugger can handle
it. Note---this option is only supported by some targets, not all
of them.
--gdwarf-3
This option is the same as the --gdwarf-2 option, except that it
allows for the possibility of the generation of extra debug
information as per version 3 of the DWARF specification. Note -
enabling this option does not guarantee the generation of any extra
information, the choice to do so is on a per target basis.
--gdwarf-4
This option is the same as the --gdwarf-2 option, except that it
allows for the possibility of the generation of extra debug
information as per version 4 of the DWARF specification. Note -
enabling this option does not guarantee the generation of any extra
information, the choice to do so is on a per target basis.
--gdwarf-5
This option is the same as the --gdwarf-2 option, except that it
allows for the possibility of the generation of extra debug
information as per version 5 of the DWARF specification. Note -
enabling this option does not guarantee the generation of any extra
information, the choice to do so is on a per target basis.
--gdwarf-sections
Instead of creating a .debug_line section, create a series of
.debug_line.foo sections where foo is the name of the corresponding
code section. For example a code section called .text.func will
have its dwarf line number information placed into a section called
.debug_line.text.func. If the code section is just called .text
then debug line section will still be called just .debug_line
without any suffix.
--gdwarf-cie-version=version
Control which version of DWARF Common Information Entries (CIEs)
are produced. When this flag is not specified the default is
version 1, though some targets can modify this default. Other
possible values for version are 3 or 4.
--generate-missing-build-notes=yes
--generate-missing-build-notes=no
These options control whether the ELF assembler should generate GNU
Build attribute notes if none are present in the input sources.
The default can be controlled by the --enable-generate-build-notes
configure option.
--gsframe
--gsframe
Create .sframe section from CFI directives.
--hash-size N
Ignored. Supported for command line compatibility with other
assemblers.
--help
Print a summary of the command-line options and exit.
--target-help
Print a summary of all target specific options and exit.
--info
Don't suppress informational messages.
--no-info
Suppress informational messages.
-I dir
Add directory dir to the search list for ".include" directives.
-J Don't warn about signed overflow.
-K Issue warnings when difference tables altered for long
displacements.
-L
--keep-locals
Keep (in the symbol table) local symbols. These symbols start with
system-specific local label prefixes, typically .L for ELF systems
or L for traditional a.out systems.
--listing-lhs-width=number
Set the maximum width, in words, of the output data column for an
assembler listing to number.
--listing-lhs-width2=number
Set the maximum width, in words, of the output data column for
continuation lines in an assembler listing to number.
--listing-rhs-width=number
Set the maximum width of an input source line, as displayed in a
listing, to number bytes.
--listing-cont-lines=number
Set the maximum number of lines printed in a listing for a single
line of input to number + 1.
--multibyte-handling=allow
--multibyte-handling=warn
--multibyte-handling=warn-sym-only
--multibyte-handling=warn_sym_only
Controls how the assembler handles multibyte characters in the
input. The default (which can be restored by using the allow
argument) is to allow such characters without complaint. Using the
warn argument will make the assembler generate a warning message
whenever any multibyte character is encountered. Using the warn-
sym-only argument will only cause a warning to be generated when a
symbol is defined with a name that contains multibyte characters.
(References to undefined symbols will not generate a warning).
--no-pad-sections
Stop the assembler for padding the ends of output sections to the
alignment of that section. The default is to pad the sections, but
this can waste space which might be needed on targets which have
tight memory constraints.
-o objfile
Name the object-file output from as objfile.
-R Fold the data section into the text section.
--reduce-memory-overheads
Ignored. Supported for compatibility with tools that pass the same
option to both the assembler and the linker.
--scfi=experimental
This option controls whether the assembler should synthesize CFI
for hand-written input. If the input already contains some
synthesizable CFI directives, the assembler ignores them and emits
a warning. Note that "--scfi=experimental" is not intended to be
used for compiler-generated code, including inline assembly. This
experimental support is work in progress. Only System V AMD64 ABI
is supported.
Each input function in assembly must begin with the ".type"
directive, and should ideally be closed off using a ".size"
directive. When using SCFI, each ".type" directive prompts GAS to
start a new FDE (a.k.a., Function Descriptor Entry). This implies
that with each ".type" directive, a previous block of instructions,
if any, is finalised as a distinct FDE.
--sectname-subst
Honor substitution sequences in section names.
--size-check=error
--size-check=warning
Issue an error or warning for invalid ELF .size directive.
--statistics
Print the maximum space (in bytes) and total time (in seconds) used
by assembly.
--strip-local-absolute
Remove local absolute symbols from the outgoing symbol table.
-v
-version
Print the as version.
--version
Print the as version and exit.
-W
--no-warn
Suppress warning messages.
--warn
Don't suppress warning messages or treat them as errors.
--fatal-warnings
Treat warnings as errors.
-w Ignored.
-x Ignored.
-Z Generate an object file even after errors.
-- | files ...
Standard input, or source files to assemble.
The following options are available when as is configured for the
64-bit mode of the ARM Architecture (AArch64).
-EB This option specifies that the output generated by the assembler
should be marked as being encoded for a big-endian processor.
-EL This option specifies that the output generated by the assembler
should be marked as being encoded for a little-endian processor.
-mabi=abi
Specify which ABI the source code uses. The recognized arguments
are: "ilp32" and "lp64", which decides the generated object file in
ELF32 and ELF64 format respectively. The default is "lp64".
-mcpu=processor[+extension...]
This option specifies the target processor. The assembler will
issue an error message if an attempt is made to assemble an
instruction which will not execute on the target processor. The
following processor names are recognized: "cortex-a34",
"cortex-a35", "cortex-a53", "cortex-a55", "cortex-a57",
"cortex-a65", "cortex-a65ae", "cortex-a72", "cortex-a73",
"cortex-a75", "cortex-a76", "cortex-a76ae", "cortex-a77",
"cortex-a78", "cortex-a78ae", "cortex-a78c", "cortex-a510",
"cortex-a520", "cortex-a710", "cortex-a720", "ares", "exynos-m1",
"falkor", "neoverse-n1", "neoverse-n2", "neoverse-e1",
"neoverse-v1", "qdf24xx", "saphira", "thunderx", "vulcan", "xgene1"
"xgene2", "cortex-r82", "cortex-x1", "cortex-x2", "cortex-x3", and
"cortex-x4". The special name "all" may be used to allow the
assembler to accept instructions valid for any supported processor,
including all optional extensions.
In addition to the basic instruction set, the assembler can be told
to accept, or restrict, various extension mnemonics that extend the
processor.
If some implementations of a particular processor can have an
extension, then then those extensions are automatically enabled.
Consequently, you will not normally have to specify any additional
extensions.
-march=architecture[+extension...]
This option specifies the target architecture. The assembler will
issue an error message if an attempt is made to assemble an
instruction which will not execute on the target architecture. The
following architecture names are recognized: "armv8-a",
"armv8.1-a", "armv8.2-a", "armv8.3-a", "armv8.4-a" "armv8.5-a",
"armv8.6-a", "armv8.7-a", "armv8.8-a", "armv8.9-a", "armv8-r",
"armv9-a", "armv9.1-a", "armv9.2-a", "armv9.3-a", "armv9.4-a" and
"armv9.5-a".
If both -mcpu and -march are specified, the assembler will use the
setting for -mcpu. If neither are specified, the assembler will
default to -mcpu=all.
The architecture option can be extended with the same instruction
set extension options as the -mcpu option. Unlike -mcpu,
extensions are not always enabled by default.
-mverbose-error
This option enables verbose error messages for AArch64 gas. This
option is enabled by default.
-mno-verbose-error
This option disables verbose error messages in AArch64 gas.
The following options are available when as is configured for an Alpha
processor.
-mcpu
This option specifies the target processor. If an attempt is made
to assemble an instruction which will not execute on the target
processor, the assembler may either expand the instruction as a
macro or issue an error message. This option is equivalent to the
".arch" directive.
The following processor names are recognized: 21064, "21064a",
21066, 21068, 21164, "21164a", "21164pc", 21264, "21264a",
"21264b", "ev4", "ev5", "lca45", "ev5", "ev56", "pca56", "ev6",
"ev67", "ev68". The special name "all" may be used to allow the
assembler to accept instructions valid for any Alpha processor.
In order to support existing practice in OSF/1 with respect to
".arch", and existing practice within MILO (the Linux ARC
bootloader), the numbered processor names (e.g. 21064) enable the
processor-specific PALcode instructions, while the "electro-vlasic"
names (e.g. "ev4") do not.
-mdebug
-no-mdebug
Enables or disables the generation of ".mdebug" encapsulation for
stabs directives and procedure descriptors. The default is to
automatically enable ".mdebug" when the first stabs directive is
seen.
-relax
This option forces all relocations to be put into the object file,
instead of saving space and resolving some relocations at assembly
time. Note that this option does not propagate all symbol
arithmetic into the object file, because not all symbol arithmetic
can be represented. However, the option can still be useful in
specific applications.
-replace
-noreplace
Enables or disables the optimization of procedure calls, both at
assemblage and at link time. These options are only available for
VMS targets and "-replace" is the default. See section 1.4.1 of
the OpenVMS Linker Utility Manual.
-g This option is used when the compiler generates debug information.
When gcc is using mips-tfile to generate debug information for
ECOFF, local labels must be passed through to the object file.
Otherwise this option has no effect.
-Gsize
A local common symbol larger than size is placed in ".bss", while
smaller symbols are placed in ".sbss".
-F
-32addr
These options are ignored for backward compatibility.
The following options are available when as is configured for an ARC
processor.
-mcpu=cpu
This option selects the core processor variant.
-EB | -EL
Select either big-endian (-EB) or little-endian (-EL) output.
-mcode-density
Enable Code Density extension instructions.
The following options are available when as is configured for the ARM
processor family.
-mcpu=processor[+extension...]
Specify which ARM processor variant is the target.
-march=architecture[+extension...]
Specify which ARM architecture variant is used by the target.
-mfpu=floating-point-format
Select which Floating Point architecture is the target.
-mfloat-abi=abi
Select which floating point ABI is in use.
-mthumb
Enable Thumb only instruction decoding.
-mapcs-32 | -mapcs-26 | -mapcs-float | -mapcs-reentrant
Select which procedure calling convention is in use.
-EB | -EL
Select either big-endian (-EB) or little-endian (-EL) output.
-mthumb-interwork
Specify that the code has been generated with interworking between
Thumb and ARM code in mind.
-mccs
Turns on CodeComposer Studio assembly syntax compatibility mode.
-k Specify that PIC code has been generated.
The following options are available when as is configured for the
Blackfin processor family.
-mcpu=processor[-sirevision]
This option specifies the target processor. The optional
sirevision is not used in assembler. It's here such that GCC can
easily pass down its "-mcpu=" option. The assembler will issue an
error message if an attempt is made to assemble an instruction
which will not execute on the target processor. The following
processor names are recognized: "bf504", "bf506", "bf512", "bf514",
"bf516", "bf518", "bf522", "bf523", "bf524", "bf525", "bf526",
"bf527", "bf531", "bf532", "bf533", "bf534", "bf535" (not
implemented yet), "bf536", "bf537", "bf538", "bf539", "bf542",
"bf542m", "bf544", "bf544m", "bf547", "bf547m", "bf548", "bf548m",
"bf549", "bf549m", "bf561", and "bf592".
-mfdpic
Assemble for the FDPIC ABI.
-mno-fdpic
-mnopic
Disable -mfdpic.
The following options are available when as is configured for the Linux
kernel BPF processor family.
@chapter BPF Dependent Features
BPF Options
-EB This option specifies that the assembler should emit big-endian
eBPF.
-EL This option specifies that the assembler should emit little-endian
eBPF.
-mdialect=dialect
This option specifies the assembly language dialect to recognize
while assembling. The assembler supports normal and pseudoc.
-misa-spec=spec
This option specifies the version of the BPF instruction set to use
when assembling. The BPF ISA versions supported are v1 v2, v3 and
v4.
The value xbpf can be specified to recognize extra instructions
that are used by GCC for testing purposes. But beware this is not
valid BPF.
-mno-relax
This option tells the assembler to not relax instructions.
Note that if no endianness option is specified in the command line, the
host endianness is used. See the info pages for documentation of the
CRIS-specific options.
The following options are available when as is configured for the C-SKY
processor family.
-march=archname
Assemble for architecture archname. The --help option lists valid
values for archname.
-mcpu=cpuname
Assemble for architecture cpuname. The --help option lists valid
values for cpuname.
-EL
-mlittle-endian
Generate little-endian output.
-EB
-mbig-endian
Generate big-endian output.
-fpic
-pic
Generate position-independent code.
-mljump
-mno-ljump
Enable/disable transformation of the short branch instructions
"jbf", "jbt", and "jbr" to "jmpi". This option is for V2
processors only. It is ignored on CK801 and CK802 targets, which
do not support the "jmpi" instruction, and is enabled by default
for other processors.
-mbranch-stub
-mno-branch-stub
Pass through "R_CKCORE_PCREL_IMM26BY2" relocations for "bsr"
instructions to the linker.
This option is only available for bare-metal C-SKY V2 ELF targets,
where it is enabled by default. It cannot be used in code that
will be dynamically linked against shared libraries.
-force2bsr
-mforce2bsr
-no-force2bsr
-mno-force2bsr
Enable/disable transformation of "jbsr" instructions to "bsr".
This option is always enabled (and -mno-force2bsr is ignored) for
CK801/CK802 targets. It is also always enabled when -mbranch-stub
is in effect.
-jsri2bsr
-mjsri2bsr
-no-jsri2bsr
-mno-jsri2bsr
Enable/disable transformation of "jsri" instructions to "bsr".
This option is enabled by default.
-mnolrw
-mno-lrw
Enable/disable transformation of "lrw" instructions into a
"movih"/"ori" pair.
-melrw
-mno-elrw
Enable/disable extended "lrw" instructions. This option is enabled
by default for CK800-series processors.
-mlaf
-mliterals-after-func
-mno-laf
-mno-literals-after-func
Enable/disable placement of literal pools after each function.
-mlabr
-mliterals-after-br
-mno-labr
-mnoliterals-after-br
Enable/disable placement of literal pools after unconditional
branches. This option is enabled by default.
-mistack
-mno-istack
Enable/disable interrupt stack instructions. This option is
enabled by default on CK801, CK802, and CK802 processors.
The following options explicitly enable certain optional instructions.
These features are also enabled implicitly by using "-mcpu=" to specify
a processor that supports it.
-mhard-float
Enable hard float instructions.
-mmp
Enable multiprocessor instructions.
-mcp
Enable coprocessor instructions.
-mcache
Enable cache prefetch instruction.
-msecurity
Enable C-SKY security instructions.
-mtrust
Enable C-SKY trust instructions.
-mdsp
Enable DSP instructions.
-medsp
Enable enhanced DSP instructions.
-mvdsp
Enable vector DSP instructions.
The following options are available when as is configured for an
Epiphany processor.
-mepiphany
Specifies that the both 32 and 16 bit instructions are allowed.
This is the default behavior.
-mepiphany16
Restricts the permitted instructions to just the 16 bit set.
The following options are available when as is configured for an H8/300
processor. @chapter H8/300 Dependent Features
Options
The Renesas H8/300 version of "as" has one machine-dependent option:
-h-tick-hex
Support H'00 style hex constants in addition to 0x00 style.
-mach=name
Sets the H8300 machine variant. The following machine names are
recognised: "h8300h", "h8300hn", "h8300s", "h8300sn", "h8300sx" and
"h8300sxn".
The following options are available when as is configured for an i386
processor.
--32 | --x32 | --64
Select the word size, either 32 bits or 64 bits. --32 implies
Intel i386 architecture, while --x32 and --64 imply AMD x86-64
architecture with 32-bit or 64-bit word-size respectively.
These options are only available with the ELF object file format,
and require that the necessary BFD support has been included (on a
32-bit platform you have to add --enable-64-bit-bfd to configure
enable 64-bit usage and use x86-64 as target platform).
-n By default, x86 GAS replaces multiple nop instructions used for
alignment within code sections with multi-byte nop instructions
such as leal 0(%esi,1),%esi. This switch disables the optimization
if a single byte nop (0x90) is explicitly specified as the fill
byte for alignment.
--divide
On SVR4-derived platforms, the character / is treated as a comment
character, which means that it cannot be used in expressions. The
--divide option turns / into a normal character. This does not
disable / at the beginning of a line starting a comment, or affect
using # for starting a comment.
-march=CPU[+EXTENSION...]
This option specifies the target processor. The assembler will
issue an error message if an attempt is made to assemble an
instruction which will not execute on the target processor. The
following processor names are recognized: "i8086", "i186", "i286",
"i386", "i486", "i586", "i686", "pentium", "pentiumpro",
"pentiumii", "pentiumiii", "pentium4", "prescott", "nocona",
"core", "core2", "corei7", "iamcu", "k6", "k6_2", "athlon",
"opteron", "k8", "amdfam10", "bdver1", "bdver2", "bdver3",
"bdver4", "znver1", "znver2", "znver3", "znver4", "znver5",
"btver1", "btver2", "generic32" and "generic64".
In addition to the basic instruction set, the assembler can be told
to accept various extension mnemonics. For example,
"-march=i686+sse4+vmx" extends i686 with sse4 and vmx. The
following extensions are currently supported: 8087, 287, 387, 687,
"cmov", "fxsr", "mmx", "sse", "sse2", "sse3", "sse4a", "ssse3",
"sse4.1", "sse4.2", "sse4", "avx", "avx2", "lahf_sahf", "monitor",
"adx", "rdseed", "prfchw", "smap", "mpx", "sha", "rdpid",
"ptwrite", "cet", "gfni", "vaes", "vpclmulqdq", "prefetchwt1",
"clflushopt", "se1", "clwb", "movdiri", "movdir64b", "enqcmd",
"serialize", "tsxldtrk", "kl", "widekl", "hreset", "avx512f",
"avx512cd", "avx512er", "avx512pf", "avx512vl", "avx512bw",
"avx512dq", "avx512ifma", "avx512vbmi", "avx512_4fmaps",
"avx512_4vnniw", "avx512_vpopcntdq", "avx512_vbmi2", "avx512_vnni",
"avx512_bitalg", "avx512_vp2intersect", "tdx", "avx512_bf16",
"avx_vnni", "avx512_fp16", "prefetchi", "avx_ifma",
"avx_vnni_int8", "cmpccxadd", "wrmsrns", "msrlist",
"avx_ne_convert", "rao_int", "fred", "lkgs", "avx_vnni_int16",
"sha512", "sm3", "sm4", "pbndkb", "avx10.1", "avx10.1/512",
"avx10.1/256", "avx10.1/128", "user_msr", "msr_imm", "apx_f",
"avx10.2", "avx10.2/512", "avx10.2/256", "avx10.2/128", "movrs",
"amx_int8", "amx_bf16", "amx_fp16", "amx_complex", "amx_transpose",
"amx_tf32", "amx_fp8" "amx_movrs", "amx_avx512", "amx_tile", "vmx",
"vmfunc", "smx", "xsave", "xsaveopt", "xsavec", "xsaves", "aes",
"pclmul", "fsgsbase", "rdrnd", "f16c", "bmi2", "fma", "movbe",
"ept", "lzcnt", "popcnt", "hle", "rtm", "tsx", "invpcid",
"clflush", "mwaitx", "clzero", "wbnoinvd", "pconfig", "waitpkg",
"uintr", "cldemote", "rdpru", "mcommit", "sev_es", "lwp", "fma4",
"xop", "cx16", "syscall", "rdtscp", "3dnow", "3dnowa", "sse4a",
"sse5", "snp", "invlpgb", "tlbsync", "svme", "gmism2", "gmiccs",
"padlockrng2", "padlockphe2" and "padlock". Note that these
extension mnemonics can be prefixed with "no" to revoke the
respective (and any dependent) functionality. Note further that
the suffixes permitted on "-march=avx10.<N>" enforce a vector
length restriction, i.e. despite these otherwise being "enabling"
options, using these suffixes will disable all insns with wider
vector or mask register operands.
When the ".arch" directive is used with -march, the ".arch"
directive will take precedent.
-mtune=CPU
This option specifies a processor to optimize for. When used in
conjunction with the -march option, only instructions of the
processor specified by the -march option will be generated.
Valid CPU values are identical to the processor list of -march=CPU.
-moperand-check=none
-moperand-check=warning
-moperand-check=error
These options control if the assembler should check certain
instruction operands or operand combinations. An example
instructions where operand size cannot be inferred from its
operands and also hasn't been specified by way of an instruction
suffix. -moperand-check=none will make the assembler not perform
these checks. -moperand-check=warning will make the assembler
issue a warning when respective checks fail, which is the default.
-moperand-check=error will make the assembler issue an error when
respective checks fail.
-msse2avx
This option specifies that the assembler should encode SSE
instructions with VEX prefix, requiring AVX to be available. SSE
instructions using extended GPRs will be encoded with EVEX prefix,
requiring AVX512 or AVX10 to be available.
-muse-unaligned-vector-move
This option specifies that the assembler should encode aligned
vector move as unaligned vector move.
-msse-check=none
-msse-check=warning
-msse-check=error
These options control if the assembler should check SSE
instructions. -msse-check=none will make the assembler not to
check SSE instructions, which is the default. -msse-check=warning
will make the assembler issue a warning for any SSE instruction.
-msse-check=error will make the assembler issue an error for any
SSE instruction.
-mavxscalar=128
-mavxscalar=256
These options control how the assembler should encode scalar AVX
instructions. -mavxscalar=128 will encode scalar AVX instructions
with 128bit vector length, which is the default. -mavxscalar=256
will encode scalar AVX instructions with 256bit vector length.
WARNING: Don't use this for production code - due to CPU errata the
resulting code may not work on certain models.
-mvexwig=0
-mvexwig=1
These options control how the assembler should encode VEX.W-ignored
(WIG) VEX instructions. -mvexwig=0 will encode WIG VEX
instructions with vex.w = 0, which is the default. -mvexwig=1 will
encode WIG EVEX instructions with vex.w = 1.
WARNING: Don't use this for production code - due to CPU errata the
resulting code may not work on certain models.
-mevexlig=128
-mevexlig=256
-mevexlig=512
These options control how the assembler should encode length-
ignored (LIG) EVEX instructions. -mevexlig=128 will encode LIG
EVEX instructions with 128bit vector length, which is the default.
-mevexlig=256 and -mevexlig=512 will encode LIG EVEX instructions
with 256bit and 512bit vector length, respectively.
-mevexwig=0
-mevexwig=1
These options control how the assembler should encode w-ignored
(WIG) EVEX instructions. -mevexwig=0 will encode WIG EVEX
instructions with evex.w = 0, which is the default. -mevexwig=1
will encode WIG EVEX instructions with evex.w = 1.
-mmnemonic=att
-mmnemonic=intel
This option specifies instruction mnemonic for matching
instructions. The ".att_mnemonic" and ".intel_mnemonic" directives
will take precedent.
-msyntax=att
-msyntax=intel
This option specifies instruction syntax when processing
instructions. The ".att_syntax" and ".intel_syntax" directives
will take precedent.
-mnaked-reg
This option specifies that registers don't require a % prefix. The
".att_syntax" and ".intel_syntax" directives will take precedent.
-madd-bnd-prefix
This option forces the assembler to add BND prefix to all branches,
even if such prefix was not explicitly specified in the source
code.
-mno-shared
On ELF target, the assembler normally optimizes out non-PLT
relocations against defined non-weak global branch targets with
default visibility. The -mshared option tells the assembler to
generate code which may go into a shared library where all non-weak
global branch targets with default visibility can be preempted.
The resulting code is slightly bigger. This option only affects
the handling of branch instructions.
-mbig-obj
On PE/COFF target this option forces the use of big object file
format, which allows more than 32768 sections.
-momit-lock-prefix=no
-momit-lock-prefix=yes
These options control how the assembler should encode lock prefix.
This option is intended as a workaround for processors, that fail
on lock prefix. This option can only be safely used with single-
core, single-thread computers -momit-lock-prefix=yes will omit all
lock prefixes. -momit-lock-prefix=no will encode lock prefix as
usual, which is the default.
-mfence-as-lock-add=no
-mfence-as-lock-add=yes
These options control how the assembler should encode lfence,
mfence and sfence. -mfence-as-lock-add=yes will encode lfence,
mfence and sfence as lock addl $0x0, (%rsp) in 64-bit mode and lock
addl $0x0, (%esp) in 32-bit mode. -mfence-as-lock-add=no will
encode lfence, mfence and sfence as usual, which is the default.
-mrelax-relocations=no
-mrelax-relocations=yes
These options control whether the assembler should generate relax
relocations, R_386_GOT32X, in 32-bit mode, or R_X86_64_GOTPCRELX
and R_X86_64_REX_GOTPCRELX, in 64-bit mode.
-mrelax-relocations=yes will generate relax relocations.
-mrelax-relocations=no will not generate relax relocations. The
default can be controlled by a configure option
--enable-x86-relax-relocations.
-mtls-check=no
-mtls-check=yes
These options control whether the assembler check tls relocation.
-mtls-check=yes will check tls relocation. -mtls-check=no will not
check tls relocation The default can be controlled by a configure
option --enable-x86-tls-check.
-malign-branch-boundary=NUM
This option controls how the assembler should align branches with
segment prefixes or NOP. NUM must be a power of 2. It should be 0
or no less than 16. Branches will be aligned within NUM byte
boundary. -malign-branch-boundary=0, which is the default, doesn't
align branches.
-malign-branch=TYPE[+TYPE...]
This option specifies types of branches to align. TYPE is
combination of jcc, which aligns conditional jumps, fused, which
aligns fused conditional jumps, jmp, which aligns unconditional
jumps, call which aligns calls, ret, which aligns rets, indirect,
which aligns indirect jumps and calls. The default is
-malign-branch=jcc+fused+jmp.
-malign-branch-prefix-size=NUM
This option specifies the maximum number of prefixes on an
instruction to align branches. NUM should be between 0 and 5. The
default NUM is 5.
-mbranches-within-32B-boundaries
This option aligns conditional jumps, fused conditional jumps and
unconditional jumps within 32 byte boundary with up to 5 segment
prefixes on an instruction. It is equivalent to
-malign-branch-boundary=32 -malign-branch=jcc+fused+jmp
-malign-branch-prefix-size=5. The default doesn't align branches.
-mlfence-after-load=no
-mlfence-after-load=yes
These options control whether the assembler should generate lfence
after load instructions. -mlfence-after-load=yes will generate
lfence. -mlfence-after-load=no will not generate lfence, which is
the default.
-mlfence-before-indirect-branch=none
-mlfence-before-indirect-branch=all
-mlfence-before-indirect-branch=register
-mlfence-before-indirect-branch=memory
These options control whether the assembler should generate lfence
before indirect near branch instructions.
-mlfence-before-indirect-branch=all will generate lfence before
indirect near branch via register and issue a warning before
indirect near branch via memory. It also implicitly sets
-mlfence-before-ret=shl when there's no explicit
-mlfence-before-ret=. -mlfence-before-indirect-branch=register
will generate lfence before indirect near branch via register.
-mlfence-before-indirect-branch=memory will issue a warning before
indirect near branch via memory.
-mlfence-before-indirect-branch=none will not generate lfence nor
issue warning, which is the default. Note that lfence won't be
generated before indirect near branch via register with
-mlfence-after-load=yes since lfence will be generated after
loading branch target register.
-mlfence-before-ret=none
-mlfence-before-ret=shl
-mlfence-before-ret=or
-mlfence-before-ret=yes
-mlfence-before-ret=not
These options control whether the assembler should generate lfence
before ret. -mlfence-before-ret=or will generate generate or
instruction with lfence. -mlfence-before-ret=shl/yes will generate
shl instruction with lfence. -mlfence-before-ret=not will generate
not instruction with lfence. -mlfence-before-ret=none will not
generate lfence, which is the default.
-mx86-used-note=no
-mx86-used-note=yes
These options control whether the assembler should generate
GNU_PROPERTY_X86_ISA_1_USED and GNU_PROPERTY_X86_FEATURE_2_USED GNU
property notes. The default can be controlled by the
--enable-x86-used-note configure option.
-mevexrcig=rne
-mevexrcig=rd
-mevexrcig=ru
-mevexrcig=rz
These options control how the assembler should encode SAE-only EVEX
instructions. -mevexrcig=rne will encode RC bits of EVEX
instruction with 00, which is the default. -mevexrcig=rd,
-mevexrcig=ru and -mevexrcig=rz will encode SAE-only EVEX
instructions with 01, 10 and 11 RC bits, respectively.
-mamd64
-mintel64
This option specifies that the assembler should accept only AMD64
or Intel64 ISA in 64-bit mode. The default is to accept common,
Intel64 only and AMD64 ISAs.
-O0 | -O | -O1 | -O2 | -Os
Optimize instruction encoding with smaller instruction size. -O
and -O1 encode 64-bit register load instructions with 64-bit
immediate as 32-bit register load instructions with 31-bit or
32-bits immediates, encode 64-bit register clearing instructions
with 32-bit register clearing instructions, encode 256-bit/512-bit
VEX/EVEX vector register clearing instructions with 128-bit VEX
vector register clearing instructions, encode 128-bit/256-bit EVEX
vector register load/store instructions with VEX vector register
load/store instructions, and encode 128-bit/256-bit EVEX packed
integer logical instructions with 128-bit/256-bit VEX packed
integer logical.
-O2 includes -O1 optimization plus encodes 256-bit/512-bit EVEX
vector register clearing instructions with 128-bit EVEX vector
register clearing instructions. In 64-bit mode VEX encoded
instructions with commutative source operands will also have their
source operands swapped if this allows using the 2-byte VEX prefix
form instead of the 3-byte one. Certain forms of AND as well as OR
with the same (register) operand specified twice will also be
changed to TEST.
-Os includes -O2 optimization plus encodes 16-bit, 32-bit and
64-bit register tests with immediate as 8-bit register test with
immediate. -O0 turns off this optimization.
The following options are available when as is configured for the
Ubicom IP2K series.
-mip2022ext
Specifies that the extended IP2022 instructions are allowed.
-mip2022
Restores the default behaviour, which restricts the permitted
instructions to just the basic IP2022 ones.
The following options are available when as is configured for the
Renesas M32C and M16C processors.
-m32c
Assemble M32C instructions.
-m16c
Assemble M16C instructions (the default).
-relax
Enable support for link-time relaxations.
-h-tick-hex
Support H'00 style hex constants in addition to 0x00 style.
The following options are available when as is configured for the
Renesas M32R (formerly Mitsubishi M32R) series.
--m32rx
Specify which processor in the M32R family is the target. The
default is normally the M32R, but this option changes it to the
M32RX.
--warn-explicit-parallel-conflicts or --Wp
Produce warning messages when questionable parallel constructs are
encountered.
--no-warn-explicit-parallel-conflicts or --Wnp
Do not produce warning messages when questionable parallel
constructs are encountered.
The following options are available when as is configured for the
Motorola 68000 series.
-l Shorten references to undefined symbols, to one word instead of
two.
-m68000 | -m68008 | -m68010 | -m68020 | -m68030
| -m68040 | -m68060 | -m68302 | -m68331 | -m68332
| -m68333 | -m68340 | -mcpu32 | -m5200
Specify what processor in the 68000 family is the target. The
default is normally the 68020, but this can be changed at
configuration time.
-m68881 | -m68882 | -mno-68881 | -mno-68882
The target machine does (or does not) have a floating-point
coprocessor. The default is to assume a coprocessor for 68020,
68030, and cpu32. Although the basic 68000 is not compatible with
the 68881, a combination of the two can be specified, since it's
possible to do emulation of the coprocessor instructions with the
main processor.
-m68851 | -mno-68851
The target machine does (or does not) have a memory-management unit
coprocessor. The default is to assume an MMU for 68020 and up.
For details about the PDP-11 machine dependent features options, see
PDP-11-Options.
-mpic | -mno-pic
Generate position-independent (or position-dependent) code. The
default is -mpic.
-mall
-mall-extensions
Enable all instruction set extensions. This is the default.
-mno-extensions
Disable all instruction set extensions.
-mextension | -mno-extension
Enable (or disable) a particular instruction set extension.
-mcpu
Enable the instruction set extensions supported by a particular
CPU, and disable all other extensions.
-mmachine
Enable the instruction set extensions supported by a particular
machine model, and disable all other extensions.
The following options are available when as is configured for a
picoJava processor.
-mb Generate "big endian" format output.
-ml Generate "little endian" format output.
The following options are available when as is configured for a PRU
processor.
-mlink-relax
Assume that LD would optimize LDI32 instructions by checking the
upper 16 bits of the expression. If they are all zeros, then LD
would shorten the LDI32 instruction to a single LDI. In such case
"as" will output DIFF relocations for diff expressions.
-mno-link-relax
Assume that LD would not optimize LDI32 instructions. As a
consequence, DIFF relocations will not be emitted.
-mno-warn-regname-label
Do not warn if a label name matches a register name. Usually
assembler programmers will want this warning to be emitted. C
compilers may want to turn this off.
The following options are available when as is configured for a MIPS
processor.
-G num
This option sets the largest size of an object that can be
referenced implicitly with the "gp" register. It is only accepted
for targets that use ECOFF format, such as a DECstation running
Ultrix. The default value is 8.
-EB Generate "big endian" format output.
-EL Generate "little endian" format output.
-mips1
-mips2
-mips3
-mips4
-mips5
-mips32
-mips32r2
-mips32r3
-mips32r5
-mips32r6
-mips64
-mips64r2
-mips64r3
-mips64r5
-mips64r6
Generate code for a particular MIPS Instruction Set Architecture
level. -mips1 is an alias for -march=r3000, -mips2 is an alias for
-march=r6000, -mips3 is an alias for -march=r4000 and -mips4 is an
alias for -march=r8000. -mips5, -mips32, -mips32r2, -mips32r3,
-mips32r5, -mips32r6, -mips64, -mips64r2, -mips64r3, -mips64r5, and
-mips64r6 correspond to generic MIPS V, MIPS32, MIPS32 Release 2,
MIPS32 Release 3, MIPS32 Release 5, MIPS32 Release 6, MIPS64,
MIPS64 Release 2, MIPS64 Release 3, MIPS64 Release 5, and MIPS64
Release 6 ISA processors, respectively.
-march=cpu
Generate code for a particular MIPS CPU.
-mtune=cpu
Schedule and tune for a particular MIPS CPU.
-mfix7000
-mno-fix7000
Cause nops to be inserted if the read of the destination register
of an mfhi or mflo instruction occurs in the following two
instructions.
-mfix-rm7000
-mno-fix-rm7000
Cause nops to be inserted if a dmult or dmultu instruction is
followed by a load instruction.
-mfix-r5900
-mno-fix-r5900
Do not attempt to schedule the preceding instruction into the delay
slot of a branch instruction placed at the end of a short loop of
six instructions or fewer and always schedule a "nop" instruction
there instead. The short loop bug under certain conditions causes
loops to execute only once or twice, due to a hardware bug in the
R5900 chip.
-mdebug
-no-mdebug
Cause stabs-style debugging output to go into an ECOFF-style
.mdebug section instead of the standard ELF .stabs sections.
-mpdr
-mno-pdr
Control generation of ".pdr" sections.
-mgp32
-mfp32
The register sizes are normally inferred from the ISA and ABI, but
these flags force a certain group of registers to be treated as 32
bits wide at all times. -mgp32 controls the size of general-
purpose registers and -mfp32 controls the size of floating-point
registers.
-mgp64
-mfp64
The register sizes are normally inferred from the ISA and ABI, but
these flags force a certain group of registers to be treated as 64
bits wide at all times. -mgp64 controls the size of general-
purpose registers and -mfp64 controls the size of floating-point
registers.
-mfpxx
The register sizes are normally inferred from the ISA and ABI, but
using this flag in combination with -mabi=32 enables an ABI variant
which will operate correctly with floating-point registers which
are 32 or 64 bits wide.
-modd-spreg
-mno-odd-spreg
Enable use of floating-point operations on odd-numbered single-
precision registers when supported by the ISA. -mfpxx implies
-mno-odd-spreg, otherwise the default is -modd-spreg.
-mips16
-no-mips16
Generate code for the MIPS 16 processor. This is equivalent to
putting ".module mips16" at the start of the assembly file.
-no-mips16 turns off this option.
-mmips16e2
-mno-mips16e2
Enable the use of MIPS16e2 instructions in MIPS16 mode. This is
equivalent to putting ".module mips16e2" at the start of the
assembly file. -mno-mips16e2 turns off this option.
-mmicromips
-mno-micromips
Generate code for the microMIPS processor. This is equivalent to
putting ".module micromips" at the start of the assembly file.
-mno-micromips turns off this option. This is equivalent to
putting ".module nomicromips" at the start of the assembly file.
-msmartmips
-mno-smartmips
Enables the SmartMIPS extension to the MIPS32 instruction set.
This is equivalent to putting ".module smartmips" at the start of
the assembly file. -mno-smartmips turns off this option.
-mips3d
-no-mips3d
Generate code for the MIPS-3D Application Specific Extension. This
tells the assembler to accept MIPS-3D instructions. -no-mips3d
turns off this option.
-mdmx
-no-mdmx
Generate code for the MDMX Application Specific Extension. This
tells the assembler to accept MDMX instructions. -no-mdmx turns
off this option.
-mdsp
-mno-dsp
Generate code for the DSP Release 1 Application Specific Extension.
This tells the assembler to accept DSP Release 1 instructions.
-mno-dsp turns off this option.
-mdspr2
-mno-dspr2
Generate code for the DSP Release 2 Application Specific Extension.
This option implies -mdsp. This tells the assembler to accept DSP
Release 2 instructions. -mno-dspr2 turns off this option.
-mdspr3
-mno-dspr3
Generate code for the DSP Release 3 Application Specific Extension.
This option implies -mdsp and -mdspr2. This tells the assembler to
accept DSP Release 3 instructions. -mno-dspr3 turns off this
option.
-mmsa
-mno-msa
Generate code for the MIPS SIMD Architecture Extension. This tells
the assembler to accept MSA instructions. -mno-msa turns off this
option.
-mxpa
-mno-xpa
Generate code for the MIPS eXtended Physical Address (XPA)
Extension. This tells the assembler to accept XPA instructions.
-mno-xpa turns off this option.
-mmt
-mno-mt
Generate code for the MT Application Specific Extension. This
tells the assembler to accept MT instructions. -mno-mt turns off
this option.
-mmcu
-mno-mcu
Generate code for the MCU Application Specific Extension. This
tells the assembler to accept MCU instructions. -mno-mcu turns off
this option.
-mcrc
-mno-crc
Generate code for the MIPS cyclic redundancy check (CRC)
Application Specific Extension. This tells the assembler to accept
CRC instructions. -mno-crc turns off this option.
-mginv
-mno-ginv
Generate code for the Global INValidate (GINV) Application Specific
Extension. This tells the assembler to accept GINV instructions.
-mno-ginv turns off this option.
-mloongson-mmi
-mno-loongson-mmi
Generate code for the Loongson MultiMedia extensions Instructions
(MMI) Application Specific Extension. This tells the assembler to
accept MMI instructions. -mno-loongson-mmi turns off this option.
-mloongson-cam
-mno-loongson-cam
Generate code for the Loongson Content Address Memory (CAM)
instructions. This tells the assembler to accept Loongson CAM
instructions. -mno-loongson-cam turns off this option.
-mloongson-ext
-mno-loongson-ext
Generate code for the Loongson EXTensions (EXT) instructions. This
tells the assembler to accept Loongson EXT instructions.
-mno-loongson-ext turns off this option.
-mloongson-ext2
-mno-loongson-ext2
Generate code for the Loongson EXTensions R2 (EXT2) instructions.
This option implies -mloongson-ext. This tells the assembler to
accept Loongson EXT2 instructions. -mno-loongson-ext2 turns off
this option.
-minsn32
-mno-insn32
Only use 32-bit instruction encodings when generating code for the
microMIPS processor. This option inhibits the use of any 16-bit
instructions. This is equivalent to putting ".set insn32" at the
start of the assembly file. -mno-insn32 turns off this option.
This is equivalent to putting ".set noinsn32" at the start of the
assembly file. By default -mno-insn32 is selected, allowing all
instructions to be used.
--construct-floats
--no-construct-floats
The --no-construct-floats option disables the construction of
double width floating point constants by loading the two halves of
the value into the two single width floating point registers that
make up the double width register. By default --construct-floats
is selected, allowing construction of these floating point
constants.
--relax-branch
--no-relax-branch
The --relax-branch option enables the relaxation of out-of-range
branches. By default --no-relax-branch is selected, causing any
out-of-range branches to produce an error.
-mignore-branch-isa
-mno-ignore-branch-isa
Ignore branch checks for invalid transitions between ISA modes.
The semantics of branches does not provide for an ISA mode switch,
so in most cases the ISA mode a branch has been encoded for has to
be the same as the ISA mode of the branch's target label.
Therefore GAS has checks implemented that verify in branch assembly
that the two ISA modes match. -mignore-branch-isa disables these
checks. By default -mno-ignore-branch-isa is selected, causing any
invalid branch requiring a transition between ISA modes to produce
an error.
-mnan=encoding
Select between the IEEE 754-2008 (-mnan=2008) or the legacy
(-mnan=legacy) NaN encoding format. The latter is the default.
--emulation=name
This option was formerly used to switch between ELF and ECOFF
output on targets like IRIX 5 that supported both. MIPS ECOFF
support was removed in GAS 2.24, so the option now serves little
purpose. It is retained for backwards compatibility.
The available configuration names are: mipself, mipslelf and
mipsbelf. Choosing mipself now has no effect, since the output is
always ELF. mipslelf and mipsbelf select little- and big-endian
output respectively, but -EL and -EB are now the preferred options
instead.
-nocpp
as ignores this option. It is accepted for compatibility with the
native tools.
--trap
--no-trap
--break
--no-break
Control how to deal with multiplication overflow and division by
zero. --trap or --no-break (which are synonyms) take a trap
exception (and only work for Instruction Set Architecture level 2
and higher); --break or --no-trap (also synonyms, and the default)
take a break exception.
-n When this option is used, as will issue a warning every time it
generates a nop instruction from a macro.
The following options are available when as is configured for a
LoongArch processor.
-fpic
-fPIC
Generate position-independent code
-fno-pic
Don't generate position-independent code (default)
The following options are available when as is configured for a Meta
processor.
"-mcpu=metac11"
Generate code for Meta 1.1.
"-mcpu=metac12"
Generate code for Meta 1.2.
"-mcpu=metac21"
Generate code for Meta 2.1.
"-mfpu=metac21"
Allow code to use FPU hardware of Meta 2.1.
See the info pages for documentation of the MMIX-specific options.
The following options are available when as is configured for a NDS32
processor.
"-O1"
Optimize for performance.
"-Os"
Optimize for space.
"-EL"
Produce little endian data output.
"-EB"
Produce little endian data output.
"-mpic"
Generate PIC.
"-mno-fp-as-gp-relax"
Suppress fp-as-gp relaxation for this file.
"-mb2bb-relax"
Back-to-back branch optimization.
"-mno-all-relax"
Suppress all relaxation for this file.
"-march=<arch name>"
Assemble for architecture <arch name> which could be v3, v3j, v3m,
v3f, v3s, v2, v2j, v2f, v2s.
"-mbaseline=<baseline>"
Assemble for baseline <baseline> which could be v2, v3, v3m.
"-mfpu-freg=FREG"
Specify a FPU configuration.
"0 8 SP / 4 DP registers"
"1 16 SP / 8 DP registers"
"2 32 SP / 16 DP registers"
"3 32 SP / 32 DP registers"
"-mabi=abi"
Specify a abi version <abi> could be v1, v2, v2fp, v2fpp.
"-m[no-]mac"
Enable/Disable Multiply instructions support.
"-m[no-]div"
Enable/Disable Divide instructions support.
"-m[no-]16bit-ext"
Enable/Disable 16-bit extension
"-m[no-]dx-regs"
Enable/Disable d0/d1 registers
"-m[no-]perf-ext"
Enable/Disable Performance extension
"-m[no-]perf2-ext"
Enable/Disable Performance extension 2
"-m[no-]string-ext"
Enable/Disable String extension
"-m[no-]reduced-regs"
Enable/Disable Reduced Register configuration (GPR16) option
"-m[no-]audio-isa-ext"
Enable/Disable AUDIO ISA extension
"-m[no-]fpu-sp-ext"
Enable/Disable FPU SP extension
"-m[no-]fpu-dp-ext"
Enable/Disable FPU DP extension
"-m[no-]fpu-fma"
Enable/Disable FPU fused-multiply-add instructions
"-mall-ext"
Turn on all extensions and instructions support
The following options are available when as is configured for a PowerPC
processor.
-a32
Generate ELF32 or XCOFF32.
-a64
Generate ELF64 or XCOFF64.
-K PIC
Set EF_PPC_RELOCATABLE_LIB in ELF flags.
-mpwrx | -mpwr2
Generate code for POWER/2 (RIOS2).
-mpwr
Generate code for POWER (RIOS1)
-m601
Generate code for PowerPC 601.
-mppc, -mppc32, -m603, -m604
Generate code for PowerPC 603/604.
-m403, -m405
Generate code for PowerPC 403/405.
-m440
Generate code for PowerPC 440. BookE and some 405 instructions.
-m464
Generate code for PowerPC 464.
-m476
Generate code for PowerPC 476.
-m7400, -m7410, -m7450, -m7455
Generate code for PowerPC 7400/7410/7450/7455.
-m750cl, -mgekko, -mbroadway
Generate code for PowerPC 750CL/Gekko/Broadway.
-m821, -m850, -m860
Generate code for PowerPC 821/850/860.
-mppc64, -m620
Generate code for PowerPC 620/625/630.
-me200z2, -me200z4
Generate code for e200 variants, e200z2 with LSP, e200z4 with SPE.
-me300
Generate code for PowerPC e300 family.
-me500, -me500x2
Generate code for Motorola e500 core complex.
-me500mc
Generate code for Freescale e500mc core complex.
-me500mc64
Generate code for Freescale e500mc64 core complex.
-me5500
Generate code for Freescale e5500 core complex.
-me6500
Generate code for Freescale e6500 core complex.
-mlsp
Enable LSP instructions. (Disables SPE and SPE2.)
-mspe
Generate code for Motorola SPE instructions. (Disables LSP.)
-mspe2
Generate code for Freescale SPE2 instructions. (Disables LSP.)
-mtitan
Generate code for AppliedMicro Titan core complex.
-mppc64bridge
Generate code for PowerPC 64, including bridge insns.
-mbooke
Generate code for 32-bit BookE.
-ma2
Generate code for A2 architecture.
-maltivec
Generate code for processors with AltiVec instructions.
-mvle
Generate code for Freescale PowerPC VLE instructions.
-mvsx
Generate code for processors with Vector-Scalar (VSX) instructions.
-mhtm
Generate code for processors with Hardware Transactional Memory
instructions.
-mpower4, -mpwr4
Generate code for Power4 architecture.
-mpower5, -mpwr5, -mpwr5x
Generate code for Power5 architecture.
-mpower6, -mpwr6
Generate code for Power6 architecture.
-mpower7, -mpwr7
Generate code for Power7 architecture.
-mpower8, -mpwr8
Generate code for Power8 architecture.
-mpower9, -mpwr9
Generate code for Power9 architecture.
-mpower10, -mpwr10
Generate code for Power10 architecture.
-mpower11, -mpwr11
Generate code for Power11 architecture.
-mfuture
Generate code for 'future' architecture.
-mcell
-mcell
Generate code for Cell Broadband Engine architecture.
-mcom
Generate code Power/PowerPC common instructions.
-many
Generate code for any architecture (PWR/PWRX/PPC).
-mregnames
Allow symbolic names for registers.
-mno-regnames
Do not allow symbolic names for registers.
-mrelocatable
Support for GCC's -mrelocatable option.
-mrelocatable-lib
Support for GCC's -mrelocatable-lib option.
-memb
Set PPC_EMB bit in ELF flags.
-mlittle, -mlittle-endian, -le
Generate code for a little endian machine.
-mbig, -mbig-endian, -be
Generate code for a big endian machine.
-msolaris
Generate code for Solaris.
-mno-solaris
Do not generate code for Solaris.
-nops=count
If an alignment directive inserts more than count nops, put a
branch at the beginning to skip execution of the nops.
The following options are available when as is configured for a RISC-V
processor.
-fpic
-fPIC
Generate position-independent code
-fno-pic
Don't generate position-independent code (default)
-march=ISA
Select the base isa, as specified by ISA. For example
-march=rv32ima. If this option and the architecture attributes
aren't set, then assembler will check the default configure setting
--with-arch=ISA.
-misa-spec=ISAspec
Select the default isa spec version. If the version of ISA isn't
set by -march, then assembler helps to set the version according to
the default chosen spec. If this option isn't set, then assembler
will check the default configure setting --with-isa-spec=ISAspec.
-mpriv-spec=PRIVspec
Select the privileged spec version. We can decide whether the CSR
is valid or not according to the chosen spec. If this option and
the privilege attributes aren't set, then assembler will check the
default configure setting --with-priv-spec=PRIVspec.
-mabi=ABI
Selects the ABI, which is either "ilp32" or "lp64", optionally
followed by "f", "d", or "q" to indicate single-precision, double-
precision, or quad-precision floating-point calling convention, or
none or "e" to indicate the soft-float calling convention ("e"
indicates a soft-float RVE ABI).
-mrelax
Take advantage of linker relaxations to reduce the number of
instructions required to materialize symbol addresses. (default)
-mno-relax
Don't do linker relaxations.
-march-attr
Generate the default contents for the riscv elf attribute section
if the .attribute directives are not set. This section is used to
record the information that a linker or runtime loader needs to
check compatibility. This information includes ISA string, stack
alignment requirement, unaligned memory accesses, and the major,
minor and revision version of privileged specification.
-mno-arch-attr
Don't generate the default riscv elf attribute section if the
.attribute directives are not set.
-mcsr-check
Enable the CSR checking for the ISA-dependent CRS and the read-only
CSR. The ISA-dependent CSR are only valid when the specific ISA is
set. The read-only CSR can not be written by the CSR instructions.
-mno-csr-check
Don't do CSR checking.
-mlittle-endian
Generate code for a little endian machine.
-mbig-endian
Generate code for a big endian machine.
See the info pages for documentation of the RX-specific options.
The following options are available when as is configured for the s390
processor family.
-m31
-m64
Select the word size, either 31/32 bits or 64 bits.
-mesa
-mzarch
Select the architecture mode, either the Enterprise System
Architecture (esa) or the z/Architecture mode (zarch).
-march=processor
Specify which s390 processor variant is the target, g5 (or arch3),
g6, z900 (or arch5), z990 (or arch6), z9-109, z9-ec (or arch7), z10
(or arch8), z196 (or arch9), zEC12 (or arch10), z13 (or arch11),
z14 (or arch12), z15 (or arch13), z16 (or arch14), or arch15.
-mregnames
-mno-regnames
Allow or disallow symbolic names for registers.
-mwarn-areg-zero
Warn whenever the operand for a base or index register has been
specified but evaluates to zero.
-mwarn-regtype-mismatch=strict
-mwarn-regtype-mismatch=relaxed
-mwarn-regtype-mismatch=no
-mno-warn-regtype-mismatch
Controls whether the assembler performs register name type checks
and generates a warning message in case of a mismatch with the
operand register type. The default (which can be restored by using
the relaxed argument) is to perform relaxed register name type
checks, which allow floating point register (FPR) names %f0 to %f15
to be specified as argument to vector register (VR) operands and
vector register (VR) names %v0 to %v15 to be specified as argument
to floating point register (FPR) operands. This is acceptable as
the FPR are embedded into the lower half of the VR. Using the
strict argument strict register name type checks are performed.
The no argument, which is equivalent to -mno-warn-regtype-mismatch,
disables any register name type checks.
The following options are available when as is configured for a
TMS320C6000 processor.
-march=arch
Enable (only) instructions from architecture arch. By default, all
instructions are permitted.
The following values of arch are accepted: "c62x", "c64x", "c64x+",
"c67x", "c67x+", "c674x".
-mdsbt
-mno-dsbt
The -mdsbt option causes the assembler to generate the
"Tag_ABI_DSBT" attribute with a value of 1, indicating that the
code is using DSBT addressing. The -mno-dsbt option, the default,
causes the tag to have a value of 0, indicating that the code does
not use DSBT addressing. The linker will emit a warning if objects
of different type (DSBT and non-DSBT) are linked together.
-mpid=no
-mpid=near
-mpid=far
The -mpid= option causes the assembler to generate the
"Tag_ABI_PID" attribute with a value indicating the form of data
addressing used by the code. -mpid=no, the default, indicates
position-dependent data addressing, -mpid=near indicates position-
independent addressing with GOT accesses using near DP addressing,
and -mpid=far indicates position-independent addressing with GOT
accesses using far DP addressing. The linker will emit a warning
if objects built with different settings of this option are linked
together.
-mpic
-mno-pic
The -mpic option causes the assembler to generate the "Tag_ABI_PIC"
attribute with a value of 1, indicating that the code is using
position-independent code addressing, The "-mno-pic" option, the
default, causes the tag to have a value of 0, indicating position-
dependent code addressing. The linker will emit a warning if
objects of different type (position-dependent and position-
independent) are linked together.
-mbig-endian
-mlittle-endian
Generate code for the specified endianness. The default is little-
endian.
The following options are available when as is configured for a TILE-Gx
processor.
-m32 | -m64
Select the word size, either 32 bits or 64 bits.
-EB | -EL
Select the endianness, either big-endian (-EB) or little-endian
(-EL).
The following option is available when as is configured for a Visium
processor.
-mtune=arch
This option specifies the target architecture. If an attempt is
made to assemble an instruction that will not execute on the target
architecture, the assembler will issue an error message.
The following names are recognized: "mcm24" "mcm" "gr5" "gr6"
The following options are available when as is configured for an Xtensa
processor.
--text-section-literals | --no-text-section-literals
Control the treatment of literal pools. The default is
--no-text-section-literals, which places literals in separate
sections in the output file. This allows the literal pool to be
placed in a data RAM/ROM. With --text-section-literals, the
literals are interspersed in the text section in order to keep them
as close as possible to their references. This may be necessary
for large assembly files, where the literals would otherwise be out
of range of the "L32R" instructions in the text section. Literals
are grouped into pools following ".literal_position" directives or
preceding "ENTRY" instructions. These options only affect literals
referenced via PC-relative "L32R" instructions; literals for
absolute mode "L32R" instructions are handled separately.
--auto-litpools | --no-auto-litpools
Control the treatment of literal pools. The default is
--no-auto-litpools, which in the absence of --text-section-literals
places literals in separate sections in the output file. This
allows the literal pool to be placed in a data RAM/ROM. With
--auto-litpools, the literals are interspersed in the text section
in order to keep them as close as possible to their references,
explicit ".literal_position" directives are not required. This may
be necessary for very large functions, where single literal pool at
the beginning of the function may not be reachable by "L32R"
instructions at the end. These options only affect literals
referenced via PC-relative "L32R" instructions; literals for
absolute mode "L32R" instructions are handled separately. When
used together with --text-section-literals, --auto-litpools takes
precedence.
--absolute-literals | --no-absolute-literals
Indicate to the assembler whether "L32R" instructions use absolute
or PC-relative addressing. If the processor includes the absolute
addressing option, the default is to use absolute "L32R"
relocations. Otherwise, only the PC-relative "L32R" relocations
can be used.
--target-align | --no-target-align
Enable or disable automatic alignment to reduce branch penalties at
some expense in code size. This optimization is enabled by
default. Note that the assembler will always align instructions
like "LOOP" that have fixed alignment requirements.
--longcalls | --no-longcalls
Enable or disable transformation of call instructions to allow
calls across a greater range of addresses. This option should be
used when call targets can potentially be out of range. It may
degrade both code size and performance, but the linker can
generally optimize away the unnecessary overhead when a call ends
up within range. The default is --no-longcalls.
--transform | --no-transform
Enable or disable all assembler transformations of Xtensa
instructions, including both relaxation and optimization. The
default is --transform; --no-transform should only be used in the
rare cases when the instructions must be exactly as specified in
the assembly source. Using --no-transform causes out of range
instruction operands to be errors.
--rename-section oldname=newname
Rename the oldname section to newname. This option can be used
multiple times to rename multiple sections.
--trampolines | --no-trampolines
Enable or disable transformation of jump instructions to allow
jumps across a greater range of addresses. This option should be
used when jump targets can potentially be out of range. In the
absence of such jumps this option does not affect code size or
performance. The default is --trampolines.
--abi-windowed | --abi-call0
Choose ABI tag written to the ".xtensa.info" section. ABI tag
indicates ABI of the assembly code. A warning is issued by the
linker on an attempt to link object files with inconsistent ABI
tags. Default ABI is chosen by the Xtensa core configuration.
The following options are available when as is configured for an Z80
processor.
@chapter Z80 Dependent Features
Command-line Options
-march=CPU[-EXT...][+EXT...]
This option specifies the target processor. The assembler will
issue an error message if an attempt is made to assemble an
instruction which will not execute on the target processor. The
following processor names are recognized: "z80", "z180", "ez80",
"gbz80", "z80n", "r800". In addition to the basic instruction set,
the assembler can be told to accept some extension mnemonics. For
example, "-march=z180+sli+infc" extends z180 with SLI instructions
and IN F,(C). The following extensions are currently supported:
"full" (all known instructions), "adl" (ADL CPU mode by default,
eZ80 only), "sli" (instruction known as SLI, SLL or SL1), "xyhl"
(instructions with halves of index registers: IXL, IXH, IYL, IYH),
"xdcb" (instructions like RotOp (II+d),R and BitOp n,(II+d),R),
"infc" (instruction IN F,(C) or IN (C)), "outc0" (instruction OUT
(C),0). Note that rather than extending a basic instruction set,
the extension mnemonics starting with "-" revoke the respective
functionality: "-march=z80-full+xyhl" first removes all default
extensions and adds support for index registers halves only.
If this option is not specified then "-march=z80+xyhl+infc" is
assumed.
-local-prefix=prefix
Mark all labels with specified prefix as local. But such label can
be marked global explicitly in the code. This option do not change
default local label prefix ".L", it is just adds new one.
-colonless
Accept colonless labels. All symbols at line begin are treated as
labels.
-sdcc
Accept assembler code produced by SDCC.
-fp-s=FORMAT
Single precision floating point numbers format. Default: ieee754
(32 bit).
-fp-d=FORMAT
Double precision floating point numbers format. Default: ieee754
(64 bit).
SEE ALSO
gcc(1), ld(1), and the Info entries for binutils and ld.
COPYRIGHT
Copyright (c) 1991-2025 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3 or
any later version published by the Free Software Foundation; with no
Invariant Sections, with no Front-Cover Texts, and with no Back-Cover
Texts. A copy of the license is included in the section entitled "GNU
Free Documentation License".
binutils-2.44 2025-05-12 AS(1)
GPROFNG-COLLECT-APP(1) Команды пользователя GPROFNG-COLLECT-APP(1)
NAME
gprofng-collect-app - Сбор данных производительности для целевого приложения
SYNOPSIS
gprofng collect app [option(s)] target [target-option(s)]
DESCRIPTION
Сбор данных производительности на целевой программе. Кроме выборки Program
Counter (PC), поддерживаются аппаратные счетчики событий и различные опции
трассировки.
Например, эта команда собирает данные производительности для исполняемого
файла с именем a.out и сохраняет собранные данные в каталоге эксперимента
с именем example.er.
$ gprofng collect app -o example.er ./a.out
OPTIONS
--version
Вывести номер версии и выйти.
--help
Вывести информацию об использовании и выйти.
-v, --verbose
По умолчанию режим подробного вывода отключен. Эта опция включает его.
-p {off | on | lo[w] | hi[gh] | <value>}
Отключить (off) или включить (on) профилирование по часам с использованием
значения выборки по умолчанию, или включить профилирование по часам
неявно путем установки гранулярности выборки (lo[w], hi[gh] или
конкретное значение в мс). По умолчанию профилирование по часам включено (-p on).
-h <ctr_def>[,<ctr_def>]
Включить профилирование аппаратных счетчиков событий и выбрать один или
несколько счетчиков. Чтобы увидеть поддерживаемые счетчики на этой системе,
используйте опцию -h без других аргументов.
-o <exp_name>
Указать имя каталога эксперимента. Имя должно заканчиваться на .er и может
содержать абсолютный путь (например, /tmp/experiment.er). Существующий
эксперимент с таким же именем не будет перезаписан.
-O <exp_name>
Это то же самое, что и опция -o, но в отличие от нее, она без предупреждения
перезаписывает существующий каталог эксперимента с таким же именем.
-C <comment_string>
Добавить до 10 строк комментариев к эксперименту. Эти комментарии
появляются в разделе заметок заголовка и могут быть получены с помощью
команды gprofng display text с опцией -header.
-j {on | off | <path>}
Управляет профилированием Java, когда цель - это виртуальная машина JVM.
Допустимые значения для этой опции:
on Записывать данные профилирования для виртуальной машины JVM и
распознавать методы, скомпилированные виртуальной машиной Java HotSpot.
Также записывать стек вызовов Java.
off Не записывать данные профилирования Java. Данные профилирования для
стеков вызовов нативного кода все равно записываются.
<path>
Записывать данные профилирования для JVM и использовать JVM,
установленную в <path>.
По умолчанию -j on.
-J <jvm-option(s)>
Указывает одну или несколько дополнительных опций, которые будут переданы
используемой JVM. Список jvm-option(s) должен быть заключен в кавычки,
если он содержит более одной опции. Элементы списка должны быть разделены
пробелами или табуляциями. Каждый элемент передается как отдельная опция
JVM. Обратите внимание, что эта опция подразумевает -j on.
-t <duration>[m|s]
Собирать данные в течение указанной длительности. Длительность может быть
одним числом, за которым может следовать m для указания минут или s для
указания секунд (по умолчанию).
Длительность также может состоять из двух чисел, разделенных знаком минус
(-). Если дано одно число, данные собираются с начала запуска до указанного
времени. Если дано два числа, данные собираются с первого времени до
второго. В случае, если второе время равно нулю, данные собираются до конца
запуска. Если дано два ненулевых числа, первое должно быть меньше второго.
-n Это используется для пробного запуска. Выводятся несколько настроек
времени выполнения, но цель не выполняется и данные производительности
не собираются.
-F {off|on|=regex}
Управляет тем, должны ли данные для дочерних процессов записываться.
Чтобы отключить/включить эту функцию, используйте off/on. Используйте =regex,
чтобы записывать данные для процессов, чье имя исполняемого файла
соответствует регулярному выражению. Используется только базовое имя
исполняемого файла, а не полный путь. Если используются пробелы или
символы, интерпретируемые оболочкой, заключите регулярное выражение
в одинарные кавычки. По умолчанию -F on.
-a {off|on|ldobjects|src|usedldobjects|usedsrc}
Указать архивирование бинарных файлов и других файлов. Кроме отключения
этой функции (off) или включения архивирования всех loadobjects и
источников (on), другие опции поддерживают более точный выбор.
Все эти опции включают архивирование, но ключевое слово управляет тем,
что именно выбрано: все объекты загрузки (ldobjects), все исходные файлы
(src), объекты загрузки, связанные с программным счетчиком (usedldobjects),
или исходные файлы, связанные с программным счетчиком (usedsrc).
По умолчанию -a ldobjects.
-S {off|on|<seconds>}
Отключить (off) или включить (on) периодический сбор выборок использования
ресурсов процесса. По умолчанию выборки происходят каждую секунду.
Используйте опцию <seconds>, чтобы изменить это. По умолчанию -S on.
-y <signal>[,r]
Управляет записью данных с сигналом, названным <signal>, называемым
сигналом паузы-восстановления. Когда данный сигнал доставляется процессу,
переключается между состояниями паузы (данные не записываются) и
восстановления (данные записываются).
По умолчанию сбор данных начинается в состоянии паузы. Если указана
необязательная r, сбор данных начинается в состоянии восстановления
и начинается немедленно.
Рекомендуется использовать SIGUSR1 или SIGUSR2 для этого, но можно
использовать любой сигнал, который не используется целью.
-l <signal>
Указать сигнал, который вызовет выборку использования ресурсов процесса.
Когда названный <signal> доставляется процессу, записывается выборка.
Сигнал можно указать с полным именем, без начальных букв "SIG", или
с номером сигнала. Обратите внимание, что команда kill может быть
использована для доставки сигнала.
Если используются обе опции -l и -y, сигнал должен быть разным.
-s <option>[,<API>]
Включить трассировку ожидания синхронизации, где <option> используется
для определения деталей трассировки (on, off, <threshold> или all).
API выбирается через настройку для <API>: n выбирает нативное/Pthreads,
j выбирает Java, а nj выбирает оба. По умолчанию -s off.
-H {off|on}
Отключить (off) или включить (on) трассировку кучи. По умолчанию -H off.
-i {off|on}
Отключить (off) или включить (on) трассировку ввода/вывод. По умолчанию -i off.
NOTES
Любое исполняемое в формате ELF (Executable and Linkable Format) может
использоваться для профилирования с gprofng. Если доступна информация
отладки, gprofng может предоставить больше деталей, но это не обязательно.
SEE ALSO
gprofng(1), gprofng-archive(1), gprofng-display-html(1),
gprofng-display-src(1), gprofng-display-text(1)
Руководство пользователя для gprofng поддерживается как руководство в формате
Texinfo. Если программы info и gprofng правильно установлены, команда info
gprofng должна предоставить доступ к этому документу.
COPYRIGHT
Copyright (c) 2022-2025 Free Software Foundation, Inc.
Разрешается копировать, распространять и/или изменять этот документ в
соответствии с условиями Лицензии GNU Free Documentation License,
версии 1.3 или любой более поздней версии, опубликованной Free Software
Foundation; без Инвариантных Разделов, без Текстов Обложки и без Текстов
Задней Обложки. Копия лицензии включена в раздел, озаглавленный "GNU
Free Documentation License".
binutils-2.44 2025-02-02 GPROFNG-COLLECT-APP(1)
GPROFNG-COLLECT-APP(1) User Commands GPROFNG-COLLECT-APP(1)
NAME
gprofng-collect-app - Collect performance data for the target
application
SYNOPSIS
gprofng collect app [option(s)] target [target-option(s)]
DESCRIPTION
Collect performance data on the target program. In addition to Program
Counter (PC) sampling, hardware event counters and various tracing
options are supported.
For example, this command collects performance data for an executable
called a.out and stores the data collected in an experiment directory
with the name example.er.
$ gprofng collect app -o example.er ./a.out
OPTIONS
--version
Print the version number and exit.
--help
Print usage information and exit.
-v, --verbose
By default, verbose mode is disabled. This option enables it.
-p {off | on | lo[w] | hi[gh] | <value>}
Disable (off) or enable (on) clock profiling using a default
sampling granularity, or enable clock profiling implicitly by
setting the sampling granularity (lo[w], hi[gh], or a specific
value in ms). By default, clock profiling is enabled (-p on).
-h <ctr_def>[,<ctr_def>]
Enable hardware event counter profiling and select one or more
counter(s). To see the supported counters on this system, use the
-h option without other arguments.
-o <exp_name>
Specify the name for the experiment directory. The name has to end
with .er and may contain an absolute path (e.g.
/tmp/experiment.er). An existing experiment with the same name
will not be overwritten.
-O <exp_name>
This is the same as the -o option, but unlike this option, silently
overwrites an existing experiment directory with the same name.
-C <comment_string>
Add up to 10 comment strings to the experiment. These comments
appear in the notes section of the header and can be retrieved with
the gprofng display text command using the -header option.
-j {on | off | <path>}
Controls Java profiling when the target is a JVM machine. The
allowed values for this option are:
on Record profiling data for the JVM machine, and recognize
methods compiled by the Java HotSpot virtual machine. Also
record Java call stacks.
off Do not record Java profiling data. Profiling data for native
call stacks is still recorded.
<path>
Records profiling data for the JVM, and use the JVM as
installed in <path>.
The default is -j on.
-J <jvm-option(s)>
Specifies one or more additional options to be passed to the JVM
used. The jvm-option(s) list must be enclosed in quotation marks
if it contains more than one option. The items in the list need to
be separated by spaces or tabs. Each item is passed as a separate
option to the JVM. Note that this option implies -j on.
-t <duration>[m|s]
Collects data for the specified duration. The duration can be a
single number, optionally followed by either m to specify minutes,
or s to specify seconds, which is the default.
The duration can also consists of two numbers separated by a minus
(-) sign. If a single number is given, data is collected from the
start of the run until the given time. If two numbers are given,
data is collected from the first time to the second. In case the
second time is zero, data is collected until the end of the run.
If two non-zero numbers are given, the first must be less than the
second.
-n This is used for a dry run. Several run-time settings are
displayed, but the target is not executed and no performance data
is collected.
-F {off|on|=regex}
Control whether descendant processes should have their data
recorded. To disable/enable this feature, use off/on. Use =regex
to record data on those processes whose executable name matches the
regular expression. Only the basename of the executable is used,
not the full path. If spaces or characters interpreted by the
shell are used, enclose the regex in single quotes. The default is
-F on.
-a {off|on|ldobjects|src|usedldobjects|usedsrc}
Specify archiving of binaries and other files. In addition to
disable this feature (off), or enable archiving off all loadobjects
and sources (on), the other options support a more refined
selection.
All of these options enable archiving, but the keyword controls
what exactly is selected: all load objects (ldobjects), all source
files (src), the loadobjects asscoiated with a program counter
(usedldobjects), or the source files associated with a program
counter (usedsrc). The default is -a ldobjects.
-S {off|on|<seconds>}
Disable (off), or enable (on) periodic sampling of process-wide
resource utilization. By default, sampling occurs every second.
Use the <seconds> option to change this. The default is -S on.
-y <signal>[,r]
Controls recording of data with the signal named <signal>, referred
to as the pause-resume signal. Whenever the given signal is
delivered to the process, switch between paused (no data is
recorded) and resumed (data is recorded) states.
By default, data collection begins in the paused state. If the
optional r is given, data collection begins in the resumed state
and data collection begins immediately.
SIGUSR1 or SIGUSR2 are recommended for this use, but any signal
that is not used by the target can be used.
-l <signal>
Specify a signal that will trigger a sample of process-wide
resource utilization. When the named <signal> is delivered to the
process, a sample is recorded.
The signal can be specified using the full name, without the
initial letters "SIG", or the signal number. Note that the kill
command can be used to deliver a signal.
If both the -l and -y options are used, the signal must be
different.
-s <option>[,<API>]
Enable synchronization wait tracing, where <option> is used to
define the specifics of the tracing (on, off, <threshold>, or all).
The API is selected through the setting for <API>: n selects
native/Pthreads, j selects Java, and nj selects both. The default
is -s off.
-H {off|on}
Disable (off), or enable (on) heap tracing. The default is -H off.
-i {off|on}
Disable (off), or enable (on) I/O tracing. The default is -i off.
NOTES
Any executable in the ELF (Executable and Linkable Format) object
format can be used for profiling with gprofng. If debug information is
available, gprofng can provide more details, but this is not a
requirement.
SEE ALSO
gprofng(1), gprofng-archive(1), gprofng-display-html(1),
gprofng-display-src(1), gprofng-display-text(1)
The user guide for gprofng is maintained as a Texinfo manual. If the
info and gprofng programs are correctly installed, the command info
gprofng should give access to this document.
COPYRIGHT
Copyright (c) 2022-2025 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3 or
any later version published by the Free Software Foundation; with no
Invariant Sections, with no Front-Cover Texts, and with no Back-Cover
Texts. A copy of the license is included in the section entitled "GNU
Free Documentation License".
binutils-2.44 2025-02-02 GPROFNG-COLLECT-APP(1)
GPROF(1) GNU GPROF(1)
NAME
gprof - отображение данных профиля графа вызовов
SYNOPSIS
gprof [ -[abcDhilLrsTvwxyz] ] [ -[ABCeEfFJnNOpPqQRStZ][name] ]
[ -I dirs ] [ -d[num] ] [ -k from/to ]
[ -m min-count ] [ -R map_file ] [ -t table-length ]
[ --[no-]annotated-source[=name] ]
[ --[no-]exec-counts[=name] ]
[ --[no-]flat-profile[=name] ] [ --[no-]graph[=name] ]
[ --[no-]time=name] [ --all-lines ] [ --brief ]
[ --debug[=level] ] [ --function-ordering ]
[ --file-ordering map_file ] [ --directory-path=dirs ]
[ --display-unused-functions ] [ --file-format=name ]
[ --file-info ] [ --help ] [ --line ] [ --inline-file-names ]
[ --min-count=n ] [ --no-static ] [ --print-path ]
[ --separate-files ] [ --static-call-graph ] [ --sum ]
[ --table-length=len ] [ --traditional ] [ --version ]
[ --width=n ] [ --ignore-non-functions ]
[ --demangle[=STYLE] ] [ --no-demangle ]
[--external-symbol-table=name]
[ image-file ] [ profile-file ... ]
DESCRIPTION
"gprof" создаёт профиль выполнения программ на C, Pascal или Fortran77.
В профиль каждой вызывающей функции включается эффект вызванных рутин.
Данные профиля берутся из файла профиля графа вызовов (по умолчанию gmon.out),
который создаётся программами, скомпилированными с опцией -pg компиляторов
"cc", "pc" и "f77". Опция -pg также связывает версии библиотечных рутин,
скомпилированных для профилирования. "Gprof" читает указанный объектный файл
(по умолчанию "a.out") и устанавливает связь между его таблицей символов
и профилем графа вызовов из gmon.out. Если указано несколько файлов профиля,
вывод "gprof" показывает сумму информации профиля из указанных файлов.
"Gprof" вычисляет количество времени, потраченного в каждой рутине. Затем
это время распространяется по рёбрам графа вызовов. Выявляются циклы,
и вызовы в цикл распределяют время цикла.
Доступно несколько форм вывода анализа.
Плоский профиль показывает, сколько времени ваша программа провела в каждой
функции и сколько раз эта функция была вызвана. Если вы просто хотите знать,
какие функции тратят больше всего циклов, это изложено кратко здесь.
Граф вызовов показывает для каждой функции, какие функции вызывали её,
какие другие функции она вызывала и сколько раз. Также есть оценка,
сколько времени было потрачено в подпрограммах каждой функции. Это может
подсказать места, где можно попытаться устранить вызовы функций,
которые используют много времени.
Аннотированный листинг исходного кода — это копия исходного кода программы,
помеченная количеством раз, когда каждая строка программы выполнялась.
OPTIONS
Эти опции определяют, какой из нескольких форматов вывода должен
производить "gprof".
Многие из этих опций принимают необязательный symspec для указания
функций, которые следует включить или исключить. Эти опции можно
указывать несколько раз с разными symspec, чтобы включить или исключить
наборы символов.
Указание любой из этих опций переопределяет значение по умолчанию (-p -q),
которое печатает плоский профиль и анализ графа вызовов для всех функций.
"-A[symspec]"
"--annotated-source[=symspec]"
Опция -A заставляет "gprof" печатать аннотированный исходный код.
Если указан symspec, выводить только для совпадающих символов.
"-b"
"--brief"
Если указана опция -b, "gprof" не печатает подробные описания,
которые пытаются объяснить значение всех полей в таблицах.
Это полезно, если вы намерены распечатать вывод или устали видеть
эти описания.
"-B"
Опция -B заставляет "gprof" печатать анализ графа вызовов.
"-C[symspec]"
"--exec-counts[=symspec]"
Опция -C заставляет "gprof" печатать подсчёт функций и количество
раз, когда каждая была вызвана. Если указан symspec, выводить
подсчёт только для совпадающих символов.
Если файл данных профиля содержит записи о счётчике базовых блоков,
указание опции -l вместе с -C приведёт к подсчёту и отображению
количества выполнений базовых блоков.
"-i"
"--file-info"
Опция -i заставляет "gprof" отображать сводную информацию о
файле(ах) данных профиля и затем выйти. Выводится количество
записей гистограммы, графа вызовов и счётчика базовых блоков.
"-I dirs"
"--directory-path=dirs"
Опция -I указывает список каталогов поиска, в которых следует
искать исходные файлы. Переменная окружения GPROF_PATH также
может использоваться для передачи этой информации. Используется
в основном для вывода аннотированного исходного кода.
"-J[symspec]"
"--no-annotated-source[=symspec]"
Опция -J заставляет "gprof" не печатать аннотированный исходный
код. Если указан symspec, "gprof" печатает аннотированный исходный
код, но исключает совпадающие символы.
"-L"
"--print-path"
Обычно имена исходных файлов печатаются без компонента пути.
Опция -L заставляет "gprof" печатать полный путь к именам
исходных файлов, который определяется из информации отладки
символов в файле образа и является относительным к каталогу,
в котором был вызван компилятор.
"-p[symspec]"
"--flat-profile[=symspec]"
Опция -p заставляет "gprof" печатать плоский профиль. Если
указан symspec, печатать плоский профиль только для совпадающих
символов.
"-P[symspec]"
"--no-flat-profile[=symspec]"
Опция -P заставляет "gprof" подавлять печать плоского профиля.
Если указан symspec, "gprof" печатает плоский профиль, но
исключает совпадающие символы.
"-q[symspec]"
"--graph[=symspec]"
Опция -q заставляет "gprof" печатать анализ графа вызовов.
Если указан symspec, печатать граф вызовов только для
совпадающих символов и их потомков.
"-Q[symspec]"
"--no-graph[=symspec]"
Опция -Q заставляет "gprof" подавлять печать графа вызовов.
Если указан symspec, "gprof" печатает граф вызовов, но
исключает совпадающие символы.
"-t"
"--table-length=num"
Опция -t заставляет перечислять num наиболее активных строк
исходного кода в каждом файле исходного кода при включённой
аннотации исходного кода. Значение по умолчанию — 10.
"-y"
"--separate-files"
Эта опция влияет только на вывод аннотированного исходного кода.
Обычно "gprof" печатает аннотированные файлы исходного кода
в стандартный вывод. Если указана эта опция, аннотированный
исходный код для файла с именем path/filename генерируется
в файле filename-ann. Если файловая система усекает filename-ann
так, что она перезаписывает оригинальное filename, "gprof"
генерирует аннотированный исходный код в файле filename.ann
вместо этого (если оригинальное имя файла имеет расширение,
это расширение заменяется на .ann).
"-Z[symspec]"
"--no-exec-counts[=symspec]"
Опция -Z заставляет "gprof" не печатать подсчёт функций и
количества раз, когда каждая была вызвана. Если указан symspec,
печатать подсчёт, но исключить совпадающие символы.
"-r"
"--function-ordering"
Опция --function-ordering заставляет "gprof" печатать
предложенный порядок функций для программы на основе данных
профиля. Эта опция предлагает порядок, который может улучшить
поведение подкачки, TLB и кэша для программы на системах,
которые поддерживают произвольный порядок функций в исполняемом
файле.
Точные детали, как заставить компоновщик размещать функции
в определённом порядке, зависят от системы и выходят за рамки
этого руководства.
"-R map_file"
"--file-ordering map_file"
Опция --file-ordering заставляет "gprof" печатать предложенный
порядок связи .o-файлов для программы на основе данных профиля.
Эта опция предлагает порядок, который может улучшить поведение
подкачки, TLB и кэша для программы на системах, которые не
поддерживают произвольный порядок функций в исполняемом файле.
Использование аргумента -a настоятельно рекомендуется с этой
опцией.
Аргумент map_file — это путь к файлу, который предоставляет
отображения имён функций на объектные файлы. Формат файла
похож на вывод программы "nm".
c-parse.o:00000000 T yyparse
c-parse.o:00000004 C yyerrflag
c-lang.o:00000000 T maybe_objc_method_name
c-lang.o:00000000 T print_lang_statistics
c-lang.o:00000000 T recognize_objc_keyword
c-decl.o:00000000 T print_lang_identifier
c-decl.o:00000000 T print_lang_type
...
Чтобы создать map_file с помощью GNU "nm", введите команду
вроде "nm --extern-only --defined-only -v --print-file-name
program-name".
"-T"
"--traditional"
Опция -T заставляет "gprof" печатать вывод в "традиционном"
стиле BSD.
"-w width"
"--width=width"
Устанавливает ширину строк вывода в width. В настоящее время
используется только при печати индекса функций в нижней части
графа вызовов.
"-x"
"--all-lines"
Эта опция влияет только на вывод аннотированного исходного кода.
По умолчанию аннотируются только строки в начале базового блока.
Если указана эта опция, каждая строка в базовом блоке аннотируется
путём повторения аннотации для первой строки. Это поведение
похоже на "tcov" с опцией -a.
"--demangle[=style]"
"--no-demangle"
Эти опции управляют тем, должны ли имена символов C++ демангловаться
при печати вывода. Значение по умолчанию — демангловать символы.
Опция "--no-demangle" может быть использована для отключения
деманглинга. Разные компиляторы имеют разные стили манглинга.
Необязательный аргумент стиля деманглинга можно использовать,
чтобы выбрать подходящий стиль деманглинга для вашего компилятора.
Analysis Options
"-a"
"--no-static"
Опция -a заставляет "gprof" подавлять печать статически
объявленных (приватных) функций. (Это функции, имена которых
не перечислены как глобальные и которые не видны за пределами
файла/функции/блока, где они определены.) Время, потраченное
в этих функциях, вызовы к ним и от них и т.д., будут отнесены
к функции, которая была загружена непосредственно перед ней
в исполняемом файле. Эта опция влияет как на плоский профиль,
так и на граф вызовов.
"-c"
"--static-call-graph"
Опция -c заставляет граф вызовов программы дополняться эвристикой,
которая осматривает пространство текста объектного файла и
идентифицирует вызовы функций в двоичном машинном коде. Поскольку
обычные записи графа вызовов генерируются только при входе
в функции, эта опция идентифицирует потомков, которые могли
быть вызваны, но никогда не были. Вызовы функций, которые не
были скомпилированы с включённым профилированием, также
идентифицируются, но только если в таблице символов есть
записи для них. Вызовы рутин динамической библиотеки обычно
не обнаруживаются этой опцией. Родители или потомки,
идентифицированные с помощью этой эвристики, указываются
в графе вызовов с количеством вызовов 0.
"-D"
"--ignore-non-functions"
Опция -D заставляет "gprof" игнорировать символы, которые не
известны как функции. Эта опция даст более точные данные профиля
на системах, где она поддерживается (например, Solaris и HPUX).
"-k from/to"
Опция -k позволяет удалить из графа вызовов любые дуги от
символов, совпадающих с symspec from, к тем, которые совпадают
с symspec to.
"-l"
"--line"
Опция -l включает профилирование по строкам, что заставляет
попадания гистограммы начисляться на отдельные строки исходного
кода, а не на функции. Эта функция работает только с программами,
скомпилированными более старыми версиями компилятора "gcc".
Новые версии "gcc" предназначены для работы с инструментом
"gcov".
Если программа была скомпилирована с включённым подсчётом
базовых блоков, эта опция также определит, сколько раз каждая
строка кода выполнялась. Хотя профилирование по строкам может
помочь изолировать, где в большой функции программа тратит
своё время, оно также значительно увеличивает время выполнения
"gprof" и увеличивает статистические неточности.
"--inline-file-names"
Эта опция заставляет "gprof" печатать исходный файл после
каждого символа как в плоском профиле, так и в графе вызовов.
Полный путь к файлу печатается, если используется с опцией -L.
"-m num"
"--min-count=num"
Эта опция влияет только на вывод счёта выполнения. Символы,
которые выполнялись менее num раз, подавляются.
"-nsymspec"
"--time=symspec"
Опция -n заставляет "gprof" в анализе графа вызовов распространять
время только для символов, совпадающих с symspec.
"-Nsymspec"
"--no-time=symspec"
Опция -n заставляет "gprof" в анализе графа вызовов не распространять
время для символов, совпадающих с symspec.
"-Sfilename"
"--external-symbol-table=filename"
Опция -S заставляет "gprof" читать внешнюю таблицу символов,
такую как /proc/kallsyms, вместо чтения таблицы символов из
указанного объектного файла (по умолчанию "a.out"). Это полезно
для профилирования модулей ядра.
"-z"
"--display-unused-functions"
Если указана опция -z, "gprof" упомянет все функции в плоском
профиле, даже те, которые никогда не вызывались и в которых
не было потрачено времени. Это полезно в сочетании с опцией -c
для обнаружения рутин, которые никогда не вызывались.
Miscellaneous Options
"-d[num]"
"--debug[=num]"
Опция -d num указывает опции отладки. Если num не указан,
включается вся отладка.
"-h"
"--help"
Опция -h печатает справку по командной строке.
"-Oname"
"--file-format=name"
Выбирает формат файлов данных профиля. Поддерживаемые форматы:
auto (по умолчанию), bsd, 4.4bsd, magic и prof (ещё не поддерживается).
"-s"
"--sum"
Опция -s заставляет "gprof" суммировать информацию в файлах
данных профиля, которые он прочитал, и записать файл данных
профиля с именем gmon.sum, который содержит всю информацию
из файлов данных профиля, прочитанных "gprof". Файл gmon.sum
может быть одним из указанных входных файлов; эффект этого
— объединение данных из других входных файлов в gmon.sum.
В конечном итоге вы можете запустить "gprof" снова без -s,
чтобы проанализировать накопленные данные в файле gmon.sum.
"-v"
"--version"
Флаг -v заставляет "gprof" печатать текущий номер версии и
затем выйти.
Deprecated Options
Эти опции были заменены более новыми версиями, которые используют symspecs.
"-e function_name"
Опция -e function сообщает "gprof" не печатать информацию о
функции function_name (и её потомках...) в графе вызовов.
Функция всё равно будет перечислена как потомок любых функций,
которые вызывают её, но её индексный номер будет показан как
[not printed]. Можно указать несколько опций -e; только одно
function_name может быть указано с каждой опцией -e.
"-E function_name"
Опция "-E function" работает как опция "-e", но время, потраченное
в функции (и потомках, которые не вызывались из других мест),
не будет использоваться для вычисления процентов времени для
графа вызовов. Можно указать несколько опций -E; только одно
function_name может быть указано с каждой опцией -E.
"-f function_name"
Опция -f function заставляет "gprof" ограничить граф вызовов
функцией function_name и её потомками (и их потомками...).
Можно указать несколько опций -f; только одно function_name
может быть указано с каждой опцией -f.
"-F function_name"
Опция -F function работает как опция "-f", но только время,
потраченное в функции и её потомках (и их потомках...), будет
использоваться для определения общего времени и процентов времени
для графа вызовов. Можно указать несколько опций -F; только одно
function_name может быть указано с каждой опцией -F. Опция -F
переопределяет опцию -E.
FILES
"a.out"
таблица имён и пространство текста.
"gmon.out"
динамический граф вызовов и профиль.
"gmon.sum"
суммированный динамический граф вызовов и профиль.
BUGS
Гранулярность выборки показывается, но остаётся статистической в лучшем
случае. Мы предполагаем, что время для каждого выполнения функции может
быть выражено как общее время для функции, делённое на количество раз,
когда функция вызывалась. Таким образом, время, распространяемое по дугам
графа вызовов к родителям функции, прямо пропорционально количеству раз,
когда эта дуга была пройдена.
Родители, которые сами не профилируются, будут иметь время своих
профилируемых потомков, распространяемое на них, но в списке графа
вызовов они будут выглядеть как спонтанно вызванные и не будут иметь
своё время, распространяемое дальше. Аналогично, перехватчики сигналов,
даже если они профилируются, будут выглядеть как спонтанные (хотя по
более сложным причинам). Любые профилируемые потомки перехватчиков
сигналов должны иметь своё время, распространяемое правильно, если только
перехватчик сигнала не был вызван во время выполнения рутины профилирования,
в таком случае всё потеряно.
Профилируемая программа должна вызвать "exit"(2) или вернуться нормально,
чтобы информация профиля была сохранена в файле gmon.out.
SEE ALSO
monitor(3), profil(2), cc(1), prof(1), и раздел Info для gprof.
"An Execution Profiler for Modular Programs" (Профилировщик выполнения
для модульных программ), S. Graham, P. Kessler, M. McKusick;
Software - Practice and Experience, Vol. 13, pp. 671-685, 1983.
"gprof: A Call Graph Execution Profiler" (gprof: Профилировщик выполнения
графа вызовов), S. Graham, P. Kessler, M. McKusick; Proceedings of the
SIGPLAN '82 Symposium on Compiler Construction, SIGPLAN Notices,
Vol. 17, No. 6, pp. 120-126, June 1982.
COPYRIGHT
Copyright (c) 1988-2025 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3 or
any later version published by the Free Software Foundation; with no
Invariant Sections, with no Front-Cover Texts, and with no Back-Cover
Texts. A copy of the license is included in the section entitled "GNU
Free Documentation License".
binutils-2.44 2025-02-02 GPROF(1)
GPROF(1) GNU GPROF(1)
NAME
gprof - display call graph profile data
SYNOPSIS
gprof [ -[abcDhilLrsTvwxyz] ] [ -[ABCeEfFJnNOpPqQRStZ][name] ]
[ -I dirs ] [ -d[num] ] [ -k from/to ]
[ -m min-count ] [ -R map_file ] [ -t table-length ]
[ --[no-]annotated-source[=name] ]
[ --[no-]exec-counts[=name] ]
[ --[no-]flat-profile[=name] ] [ --[no-]graph[=name] ]
[ --[no-]time=name] [ --all-lines ] [ --brief ]
[ --debug[=level] ] [ --function-ordering ]
[ --file-ordering map_file ] [ --directory-path=dirs ]
[ --display-unused-functions ] [ --file-format=name ]
[ --file-info ] [ --help ] [ --line ] [ --inline-file-names ]
[ --min-count=n ] [ --no-static ] [ --print-path ]
[ --separate-files ] [ --static-call-graph ] [ --sum ]
[ --table-length=len ] [ --traditional ] [ --version ]
[ --width=n ] [ --ignore-non-functions ]
[ --demangle[=STYLE] ] [ --no-demangle ]
[--external-symbol-table=name]
[ image-file ] [ profile-file ... ]
DESCRIPTION
"gprof" produces an execution profile of C, Pascal, or Fortran77
programs. The effect of called routines is incorporated in the profile
of each caller. The profile data is taken from the call graph profile
file (gmon.out default) which is created by programs that are compiled
with the -pg option of "cc", "pc", and "f77". The -pg option also
links in versions of the library routines that are compiled for
profiling. "Gprof" reads the given object file (the default is
"a.out") and establishes the relation between its symbol table and the
call graph profile from gmon.out. If more than one profile file is
specified, the "gprof" output shows the sum of the profile information
in the given profile files.
"Gprof" calculates the amount of time spent in each routine. Next,
these times are propagated along the edges of the call graph. Cycles
are discovered, and calls into a cycle are made to share the time of
the cycle.
Several forms of output are available from the analysis.
The flat profile shows how much time your program spent in each
function, and how many times that function was called. If you simply
want to know which functions burn most of the cycles, it is stated
concisely here.
The call graph shows, for each function, which functions called it,
which other functions it called, and how many times. There is also an
estimate of how much time was spent in the subroutines of each
function. This can suggest places where you might try to eliminate
function calls that use a lot of time.
The annotated source listing is a copy of the program's source code,
labeled with the number of times each line of the program was executed.
OPTIONS
These options specify which of several output formats "gprof" should
produce.
Many of these options take an optional symspec to specify functions to
be included or excluded. These options can be specified multiple
times, with different symspecs, to include or exclude sets of symbols.
Specifying any of these options overrides the default (-p -q), which
prints a flat profile and call graph analysis for all functions.
"-A[symspec]"
"--annotated-source[=symspec]"
The -A option causes "gprof" to print annotated source code. If
symspec is specified, print output only for matching symbols.
"-b"
"--brief"
If the -b option is given, "gprof" doesn't print the verbose blurbs
that try to explain the meaning of all of the fields in the tables.
This is useful if you intend to print out the output, or are tired
of seeing the blurbs.
"-B"
The -B option causes "gprof" to print the call graph analysis.
"-C[symspec]"
"--exec-counts[=symspec]"
The -C option causes "gprof" to print a tally of functions and the
number of times each was called. If symspec is specified, print
tally only for matching symbols.
If the profile data file contains basic-block count records,
specifying the -l option, along with -C, will cause basic-block
execution counts to be tallied and displayed.
"-i"
"--file-info"
The -i option causes "gprof" to display summary information about
the profile data file(s) and then exit. The number of histogram,
call graph, and basic-block count records is displayed.
"-I dirs"
"--directory-path=dirs"
The -I option specifies a list of search directories in which to
find source files. Environment variable GPROF_PATH can also be
used to convey this information. Used mostly for annotated source
output.
"-J[symspec]"
"--no-annotated-source[=symspec]"
The -J option causes "gprof" not to print annotated source code.
If symspec is specified, "gprof" prints annotated source, but
excludes matching symbols.
"-L"
"--print-path"
Normally, source filenames are printed with the path component
suppressed. The -L option causes "gprof" to print the full
pathname of source filenames, which is determined from symbolic
debugging information in the image file and is relative to the
directory in which the compiler was invoked.
"-p[symspec]"
"--flat-profile[=symspec]"
The -p option causes "gprof" to print a flat profile. If symspec
is specified, print flat profile only for matching symbols.
"-P[symspec]"
"--no-flat-profile[=symspec]"
The -P option causes "gprof" to suppress printing a flat profile.
If symspec is specified, "gprof" prints a flat profile, but
excludes matching symbols.
"-q[symspec]"
"--graph[=symspec]"
The -q option causes "gprof" to print the call graph analysis. If
symspec is specified, print call graph only for matching symbols
and their children.
"-Q[symspec]"
"--no-graph[=symspec]"
The -Q option causes "gprof" to suppress printing the call graph.
If symspec is specified, "gprof" prints a call graph, but excludes
matching symbols.
"-t"
"--table-length=num"
The -t option causes the num most active source lines in each
source file to be listed when source annotation is enabled. The
default is 10.
"-y"
"--separate-files"
This option affects annotated source output only. Normally,
"gprof" prints annotated source files to standard-output. If this
option is specified, annotated source for a file named
path/filename is generated in the file filename-ann. If the
underlying file system would truncate filename-ann so that it
overwrites the original filename, "gprof" generates annotated
source in the file filename.ann instead (if the original file name
has an extension, that extension is replaced with .ann).
"-Z[symspec]"
"--no-exec-counts[=symspec]"
The -Z option causes "gprof" not to print a tally of functions and
the number of times each was called. If symspec is specified,
print tally, but exclude matching symbols.
"-r"
"--function-ordering"
The --function-ordering option causes "gprof" to print a suggested
function ordering for the program based on profiling data. This
option suggests an ordering which may improve paging, tlb and cache
behavior for the program on systems which support arbitrary
ordering of functions in an executable.
The exact details of how to force the linker to place functions in
a particular order is system dependent and out of the scope of this
manual.
"-R map_file"
"--file-ordering map_file"
The --file-ordering option causes "gprof" to print a suggested .o
link line ordering for the program based on profiling data. This
option suggests an ordering which may improve paging, tlb and cache
behavior for the program on systems which do not support arbitrary
ordering of functions in an executable.
Use of the -a argument is highly recommended with this option.
The map_file argument is a pathname to a file which provides
function name to object file mappings. The format of the file is
similar to the output of the program "nm".
c-parse.o:00000000 T yyparse
c-parse.o:00000004 C yyerrflag
c-lang.o:00000000 T maybe_objc_method_name
c-lang.o:00000000 T print_lang_statistics
c-lang.o:00000000 T recognize_objc_keyword
c-decl.o:00000000 T print_lang_identifier
c-decl.o:00000000 T print_lang_type
...
To create a map_file with GNU "nm", type a command like "nm
--extern-only --defined-only -v --print-file-name program-name".
"-T"
"--traditional"
The -T option causes "gprof" to print its output in "traditional"
BSD style.
"-w width"
"--width=width"
Sets width of output lines to width. Currently only used when
printing the function index at the bottom of the call graph.
"-x"
"--all-lines"
This option affects annotated source output only. By default, only
the lines at the beginning of a basic-block are annotated. If this
option is specified, every line in a basic-block is annotated by
repeating the annotation for the first line. This behavior is
similar to "tcov"'s -a.
"--demangle[=style]"
"--no-demangle"
These options control whether C++ symbol names should be demangled
when printing output. The default is to demangle symbols. The
"--no-demangle" option may be used to turn off demangling.
Different compilers have different mangling styles. The optional
demangling style argument can be used to choose an appropriate
demangling style for your compiler.
Analysis Options
"-a"
"--no-static"
The -a option causes "gprof" to suppress the printing of statically
declared (private) functions. (These are functions whose names are
not listed as global, and which are not visible outside the
file/function/block where they were defined.) Time spent in these
functions, calls to/from them, etc., will all be attributed to the
function that was loaded directly before it in the executable file.
This option affects both the flat profile and the call graph.
"-c"
"--static-call-graph"
The -c option causes the call graph of the program to be augmented
by a heuristic which examines the text space of the object file and
identifies function calls in the binary machine code. Since normal
call graph records are only generated when functions are entered,
this option identifies children that could have been called, but
never were. Calls to functions that were not compiled with
profiling enabled are also identified, but only if symbol table
entries are present for them. Calls to dynamic library routines
are typically not found by this option. Parents or children
identified via this heuristic are indicated in the call graph with
call counts of 0.
"-D"
"--ignore-non-functions"
The -D option causes "gprof" to ignore symbols which are not known
to be functions. This option will give more accurate profile data
on systems where it is supported (Solaris and HPUX for example).
"-k from/to"
The -k option allows you to delete from the call graph any arcs
from symbols matching symspec from to those matching symspec to.
"-l"
"--line"
The -l option enables line-by-line profiling, which causes
histogram hits to be charged to individual source code lines,
instead of functions. This feature only works with programs
compiled by older versions of the "gcc" compiler. Newer versions
of "gcc" are designed to work with the "gcov" tool instead.
If the program was compiled with basic-block counting enabled, this
option will also identify how many times each line of code was
executed. While line-by-line profiling can help isolate where in a
large function a program is spending its time, it also
significantly increases the running time of "gprof", and magnifies
statistical inaccuracies.
"--inline-file-names"
This option causes "gprof" to print the source file after each
symbol in both the flat profile and the call graph. The full path
to the file is printed if used with the -L option.
"-m num"
"--min-count=num"
This option affects execution count output only. Symbols that are
executed less than num times are suppressed.
"-nsymspec"
"--time=symspec"
The -n option causes "gprof", in its call graph analysis, to only
propagate times for symbols matching symspec.
"-Nsymspec"
"--no-time=symspec"
The -n option causes "gprof", in its call graph analysis, not to
propagate times for symbols matching symspec.
"-Sfilename"
"--external-symbol-table=filename"
The -S option causes "gprof" to read an external symbol table file,
such as /proc/kallsyms, rather than read the symbol table from the
given object file (the default is "a.out"). This is useful for
profiling kernel modules.
"-z"
"--display-unused-functions"
If you give the -z option, "gprof" will mention all functions in
the flat profile, even those that were never called, and that had
no time spent in them. This is useful in conjunction with the -c
option for discovering which routines were never called.
Miscellaneous Options
"-d[num]"
"--debug[=num]"
The -d num option specifies debugging options. If num is not
specified, enable all debugging.
"-h"
"--help"
The -h option prints command line usage.
"-Oname"
"--file-format=name"
Selects the format of the profile data files. Recognized formats
are auto (the default), bsd, 4.4bsd, magic, and prof (not yet
supported).
"-s"
"--sum"
The -s option causes "gprof" to summarize the information in the
profile data files it read in, and write out a profile data file
called gmon.sum, which contains all the information from the
profile data files that "gprof" read in. The file gmon.sum may be
one of the specified input files; the effect of this is to merge
the data in the other input files into gmon.sum.
Eventually you can run "gprof" again without -s to analyze the
cumulative data in the file gmon.sum.
"-v"
"--version"
The -v flag causes "gprof" to print the current version number, and
then exit.
Deprecated Options
These options have been replaced with newer versions that use symspecs.
"-e function_name"
The -e function option tells "gprof" to not print information about
the function function_name (and its children...) in the call graph.
The function will still be listed as a child of any functions that
call it, but its index number will be shown as [not printed]. More
than one -e option may be given; only one function_name may be
indicated with each -e option.
"-E function_name"
The "-E function" option works like the "-e" option, but time spent
in the function (and children who were not called from anywhere
else), will not be used to compute the percentages-of-time for the
call graph. More than one -E option may be given; only one
function_name may be indicated with each -E option.
"-f function_name"
The -f function option causes "gprof" to limit the call graph to
the function function_name and its children (and their
children...). More than one -f option may be given; only one
function_name may be indicated with each -f option.
"-F function_name"
The -F function option works like the "-f" option, but only time
spent in the function and its children (and their children...) will
be used to determine total-time and percentages-of-time for the
call graph. More than one -F option may be given; only one
function_name may be indicated with each -F option. The -F option
overrides the -E option.
FILES
"a.out"
the namelist and text space.
"gmon.out"
dynamic call graph and profile.
"gmon.sum"
summarized dynamic call graph and profile.
BUGS
The granularity of the sampling is shown, but remains statistical at
best. We assume that the time for each execution of a function can be
expressed by the total time for the function divided by the number of
times the function is called. Thus the time propagated along the call
graph arcs to the function's parents is directly proportional to the
number of times that arc is traversed.
Parents that are not themselves profiled will have the time of their
profiled children propagated to them, but they will appear to be
spontaneously invoked in the call graph listing, and will not have
their time propagated further. Similarly, signal catchers, even though
profiled, will appear to be spontaneous (although for more obscure
reasons). Any profiled children of signal catchers should have their
times propagated properly, unless the signal catcher was invoked during
the execution of the profiling routine, in which case all is lost.
The profiled program must call "exit"(2) or return normally for the
profiling information to be saved in the gmon.out file.
SEE ALSO
monitor(3), profil(2), cc(1), prof(1), and the Info entry for gprof.
"An Execution Profiler for Modular Programs", by S. Graham, P. Kessler,
M. McKusick; Software - Practice and Experience, Vol. 13, pp. 671-685,
1983.
"gprof: A Call Graph Execution Profiler", by S. Graham, P. Kessler, M.
McKusick; Proceedings of the SIGPLAN '82 Symposium on Compiler
Construction, SIGPLAN Notices, Vol. 17, No 6, pp. 120-126, June 1982.
COPYRIGHT
Copyright (c) 1988-2025 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3 or
any later version published by the Free Software Foundation; with no
Invariant Sections, with no Front-Cover Texts, and with no Back-Cover
Texts. A copy of the license is included in the section entitled "GNU
Free Documentation License".
binutils-2.44 2025-02-02 GPROF(1)
AR(1) Инструменты разработки GNU AR(1)
NAME
ar - создание, модификация и извлечение из архивов
SYNOPSIS
ar [-X32_64] [-]p[mod] [--plugin name] [--target bfdname] [--output
dirname] [--record-libdeps libdeps] [--thin] [relpos] [count] archive
[member...]
DESCRIPTION
Программа GNU ar создаёт, модифицирует и извлекает файлы из архивов. Архив
представляет собой один файл, содержащий коллекцию других файлов в структуре,
которая позволяет извлечь исходные отдельные файлы (называемые членами архива).
Содержимое, режим (права доступа), временная метка, владелец и группа исходных
файлов сохраняются в архиве и могут быть восстановлены при извлечении.
GNU ar может поддерживать архивы, чьи члены имеют имена любой длины;
однако, в зависимости от конфигурации ar на вашей системе, может быть
наложен лимит на длину имени члена для совместимости с форматами архивов,
поддерживаемыми другими инструментами. Если такой лимит существует, он часто
составляет 15 символов (типично для форматов, связанных с a.out) или 16
символов (типично для форматов, связанных с coff).
ar считается утилитой для бинарных файлов, поскольку архивы такого рода
чаще всего используются как библиотеки, содержащие часто используемые
подпрограммы. Поскольку библиотеки часто зависят от других библиотек, ar может
также записывать зависимости библиотеки, если указан параметр --record-libdeps.
ar создаёт индекс символов, определённых в релокационных модулях объектов
в архиве, если вы укажете модификатор s. После создания этот индекс
обновляется в архиве при любом изменении его содержимого (кроме операции
обновления q). Архив с таким индексом ускоряет связывание с библиотекой и
позволяет подпрограммам в библиотеке вызывать друг друга без учёта их
размещения в архиве.
Вы можете использовать nm -s или nm --print-armap для вывода этого индексного
таблицы. Если в архиве отсутствует таблица, то другую форму ar, называемую
ranlib, можно использовать для добавления только таблицы.
GNU ar может опционально создавать тонкий архив, который содержит индекс
символов и ссылки на оригинальные копии файлов-членов архива. Это полезно
для создания библиотек для использования в локальном дереве сборки, где
релокационные объекты ожидаются доступными, а копирование содержимого
каждого объекта только потратит время и место.
Архив может быть либо тонким, либо обычным. Он не может быть обоими
одновременно. После создания формата архива изменить нельзя, не удалив его
сначала и не создав новый на его месте.
Тонкие архивы также уплощаются, так что добавление одного тонкого архива
в другой тонкий архив не создаст вложенности, как это произошло бы с обычным
архивом. Вместо этого элементы первого архива добавляются индивидуально
во второй архив.
Пути к элементам архива хранятся относительно самого архива.
GNU ar предназначен для совместимости с двумя разными возможностями. Вы
можете управлять его работой с помощью опций командной строки, как в разных
вариантах ar в системах Unix; или, если вы укажете единственную опцию
командной строки -M, вы можете управлять им с помощью скрипта, подаваемого
через стандартный ввод, как в программе "librarian" от MRI.
OPTIONS
GNU ar позволяет смешивать код операции p и флаги модификаторов mod в
любом порядке в первом аргументе командной строки.
Если желаете, вы можете начать первый аргумент командной строки с тире.
Ключ p определяет, какую операцию выполнить; это может быть любая из
следующих, но вы должны указать только одну из них:
d Удалить модули из архива. Укажите имена модулей для удаления как
member...; архив остаётся неизменным, если вы не укажете файлы
для удаления.
Если указан модификатор v, ar перечисляет каждый модуль по мере
его удаления.
m Используйте эту операцию для перемещения членов в архиве.
Порядок членов в архиве может повлиять на связывание программ с
помощью библиотеки, если символ определён в более чем одном члене.
Если модификаторы не используются с "m", любые члены, которые вы
укажете в аргументах member, перемещаются в конец архива; вы можете
использовать модификаторы a, b или i, чтобы переместить их в
указанное место вместо этого.
p Вывести указанных членов архива в стандартный вывод. Если указан
модификатор v, показать имя члена перед копированием его содержимого
в стандартный вывод.
Если вы не укажете аргументы member, все файлы в архиве будут
выведены.
q Быстрое добавление; Исторически, добавить файлы member... в конец
архива, без проверки на замену.
Модификаторы a, b и i не влияют на эту операцию; новые члены
всегда размещаются в конце архива.
Модификатор v заставляет ar перечислять каждый файл по мере
добавления.
Поскольку цель этой операции - скорость, реализации ar имеют
возможность не обновлять таблицу символов архива, если она существует.
Однако слишком многие разные системы предполагают, что таблицы
символов всегда актуальны, поэтому GNU ar перестроит таблицу даже
при быстром добавлении.
Примечание - GNU ar рассматривает команду qs как синоним для r -
замена уже существующих файлов в архиве и добавление новых в конец.
r Вставить файлы member... в архив (с заменой). Эта операция отличается
от q в том, что любые ранее существующие члены удаляются, если
их имена совпадают с добавляемыми.
Если один из файлов, указанных в member..., не существует, ar
отобразит сообщение об ошибке и оставит неизменёнными любые
существующие члены архива с этим именем.
По умолчанию, новые члены добавляются в конец файла; но вы можете
использовать один из модификаторов a, b или i, чтобы запросить
размещение относительно существующего члена.
Модификатор v в сочетании с этой операцией вызывает вывод строки
для каждого вставленного файла, вместе с одной из букв a или r,
чтобы указать, был ли файл добавлен (старый член не удалён) или
заменён.
s Добавить индекс в архив или обновить его, если он уже существует.
Обратите внимание, что эта команда является исключением из правила,
что может быть только один буквенный код команды, поскольку её можно
использовать как команду или модификатор. В любом случае она делает
то же самое.
t Отобразить таблицу, перечисляющую содержимое архива или тех файлов,
которые указаны в member... и присутствуют в архиве.
Нормально отображаются только имена членов, но если указан
модификатор O, то также отображаются соответствующие смещения
членов. Наконец, чтобы увидеть режимы (права доступа), временную
метку, владельца, группу и размер, следует включить модификатор v.
Если вы не укажете member, все файлы в архиве будут перечислены.
Если в архиве есть более одного файла с одинаковым именем (скажем,
fie) в архиве (скажем, b.a), ar t b.a fie перечислит только первый
экземпляр; чтобы увидеть все, вы должны запросить полный список -
в нашем примере, ar t b.a.
x Извлечь члены (с именами member) из архива. Вы можете использовать
модификатор v с этой операцией, чтобы ar перечислял каждое имя
по мере извлечения.
Если вы не укажете member, все файлы в архиве будут извлечены.
Файлы нельзя извлечь из тонкого архива, и есть ограничения на
извлечение из архивов, созданных с P: Пути не должны быть абсолютными,
не должны содержать "..", и любые поддиректории в путях должны
существовать. Если вы хотите избежать этих ограничений, используйте
опцию --output для указания выходной директории.
Несколько модификаторов (mod) могут сразу следовать за ключом p, чтобы
указать вариации поведения операции:
a Добавить новые файлы после существующего члена архива. Если вы используете
модификатор a, имя существующего члена архива должно быть
указано как аргумент relpos перед указанием архива.
b Добавить новые файлы перед существующим членом архива. Если вы используете
модификатор b, имя существующего члена архива должно быть
указано как аргумент relpos перед указанием архива. (то же, что и i).
c Создать архив. Указанный архив всегда создаётся, если он не существует,
при запросе обновления. Но выдаётся предупреждение, если вы не
укажете заранее, что ожидаете создать его, используя этот модификатор.
D Работать в детерминированном режиме. При добавлении файлов и индекса
архива используйте ноль для UIDs, GIDs, временных меток и
последовательные режимы файлов для всех файлов. Когда эта опция
используется, если ar используется с одинаковыми опциями и
одинаковыми входными файлами, несколько запусков создадут одинаковые
выходные файлы независимо от владельцев, групп, режимов файлов
или временных меток входных файлов.
Если binutils был настроен с --enable-deterministic-archives,
то этот режим включён по умолчанию. Его можно отключить с помощью
модификатора U ниже.
f Обрезать имена в архиве. GNU ar обычно разрешает имена файлов любой
длины. Это приведёт к созданию архивов, которые не совместимы
с родной программой ar на некоторых системах. Если это вызывает
беспокойство, модификатор f можно использовать для обрезания имён
файлов при помещении их в архив.
i Вставить новые файлы перед существующим членом архива. Если вы используете
модификатор i, имя существующего члена архива должно быть
указано как аргумент relpos перед указанием архива. (то же, что и b).
l Указать зависимости этой библиотеки. Зависимости должны немедленно
следовать за этим символом опции, должны использовать тот же
синтаксис, что и командная строка линкера, и должны быть указаны
в одном аргументе. Т.е., если несколько элементов нужны, их нужно
заключить в кавычки, чтобы сформировать один аргумент командной
строки. Например: l "-L/usr/local/lib -lmydep1 -lmydep2"
N Использовать параметр count. Это используется, если в архиве несколько
записей с одинаковым именем. Извлечь или удалить экземпляр count
с данным именем из архива.
o Сохранить оригинальные даты членов при их извлечении. Если вы не
укажете этот модификатор, файлы, извлечённые из архива, будут
помечены временем извлечения.
O Отобразить смещения членов внутри архива. Используйте вместе с опцией t.
P Использовать полный путь при сопоставлении или хранении имён в архиве.
Архивы, созданные с полными путями, не соответствуют POSIX,
и поэтому могут не работать с инструментами, кроме актуальных
инструментов GNU. Модификация таких архивов с помощью GNU ar без
использования P удалит полные пути, если архив не является тонким.
Обратите внимание, что P может быть полезен при добавлении файлов
в тонкий архив, поскольку r без P игнорирует путь при выборе,
какой элемент заменить. Таким образом
ar rcST archive.a subdir/file1 subdir/file2 file1
приведёт к замене первого "subdir/file1" на "file1" из текущей
директории. Добавление P предотвратит эту замену.
s Записать индекс файлов объектов в архив или обновить существующий,
даже если в архиве нет других изменений. Вы можете использовать
этот флаг модификатора как с любой операцией, так и отдельно.
Запуск ar s на архиве эквивалентен запуску ranlib на нём.
S Не генерировать таблицу символов архива. Это может ускорить создание
большой библиотеки в несколько шагов. Получившийся архив нельзя
использовать с линкером. Чтобы создать таблицу символов, вы должны
исключить модификатор S в последнем запуске ar или запустить ranlib
на архиве.
T Устаревший синоним для --thin. T не рекомендуется, потому что в многих
реализациях ar T имеет другое значение, как указано в X/Open
System Interface.
u Нормально ar r... вставляет все перечисленные файлы в архив. Если вы
хотите вставить только те из перечисленных файлов, которые новее
существующих членов с теми же именами, используйте этот модификатор.
Модификатор u разрешается только для операции r (замена). В
частности, комбинация qu не разрешается, поскольку проверка
временных меток устранит любое преимущество в скорости от операции q.
Примечание - если архив был создан в детерминированном режиме, напр.
с использованием модификатора D, то замена всегда произойдёт и
модификатор u будет неэффективным.
U Не работать в детерминированном режиме. Это обратное модификатору D,
выше: добавленные файлы и индекс архива получат фактические значения
UID, GID, временных меток и режимов файлов.
Это значение по умолчанию, если binutils был настроен без
--enable-deterministic-archives.
v Этот модификатор запрашивает подробную версию операции. Многие
операции отображавают дополнительную информацию, такую как
обработанные имена файлов, когда к ним добавлен модификатор v.
V Этот модификатор показывает номер версии ar.
Программа ar также поддерживает некоторые опции командной строки, которые
не являются ни модификаторами, ни действиями, но которые изменяют её
поведение определённым образом:
--help
Отобразить список поддерживаемых опций командной строки ar и выйти.
--version
Отобразить информацию о версии ar и выйти.
-X32_64
ar игнорирует начальную опцию, написанную как -X32_64, для
совместимости с AIX. Поведение, производимое этой опцией, является
значением по умолчанию для GNU ar. ar не поддерживает другие опции -X;
в частности, он не поддерживает -X32, которая является значением
по умолчанию для ar AIX.
--plugin name
Опциональный ключ командной строки --plugin name заставляет ar
загрузить плагин с именем name, который добавляет поддержку
дополнительных форматов файлов, включая файлы объектов с
информацией оптимизации во время связывания.
Эта опция доступна только если инструментарий был построен с
включённой поддержкой плагинов.
Если --plugin не предоставлен, но поддержка плагинов включена,
то ar перебирает файлы в ${libdir}/bfd-plugins в алфавитном порядке,
и первый плагин, который заявляет о файле объекта, используется.
Пожалуйста, обратите внимание, что этот каталог поиска плагинов
не тот, который используется опцией ld -plugin. Чтобы заставить ar
использовать плагин линкера, его нужно скопировать в каталог
${libdir}/bfd-plugins. Для компиляций на основе GCC плагин линкера
называется liblto_plugin.so.0.0.0. Для компиляций на основе Clang
он называется LLVMgold.so. Плагин GCC всегда обратно совместим
с более ранними версиями, так что достаточно скопировать
последнюю.
--target target
Опциональный ключ командной строки --target bfdname указывает,
что члены архива находятся в формате кода объектов, отличном от
формата по умолчанию вашей системы. См.
--output dirname
Опция --output может использоваться для указания пути к директории,
в которую должны извлекаться члены архива. Если эта опция не
указана, будет использована текущая директория.
Примечание - наличие этой опции подразумевает операцию извлечения x,
но опция всё равно должна быть включена в командной строке.
--record-libdeps libdeps
Опция --record-libdeps идентична модификатору l, просто в длинной форме.
--thin
Сделать указанный архив тонким архивом. Если он уже существует
и является обычным архивом, существующие члены должны быть
доступны в той же директории, что и archive.
@file
Читать опции командной строки из файла. Прочитанные опции
вставляются на место оригинальной опции @file. Если файл не
существует или не может быть прочитан, опция будет обработана
буквально, без удаления.
Опции в файле разделяются пробелами. Пробельный символ может быть
включён в опцию путём заключения всей опции в одинарные или
двойные кавычки. Любые символы (включая обратный слэш) могут быть
включены путём добавления обратного слэша перед символом для
включения. Файл может сам содержать дополнительные опции @file;
любые такие опции будут обработаны рекурсивно.
SEE ALSO
nm(1), ranlib(1) и записи Info для binutils.
COPYRIGHT
Copyright (c) 1991-2025 Free Software Foundation, Inc.
Разрешается копировать, распространять и/или модифицировать этот документ
в соответствии с условиями GNU Free Documentation License, Version 1.3 или
любой более поздней версии, опубликованной Free Software Foundation; без
Инвариантных Разделов, без Текстов на Обложке и без Текстов на Задней
Обложке. Копия лицензии включена в раздел, озаглавленный "GNU Free
Documentation License".
binutils-2.44 2025-05-12 AR(1)
AR(1) GNU Development Tools AR(1)
NAME
ar - create, modify, and extract from archives
SYNOPSIS
ar [-X32_64] [-]p[mod] [--plugin name] [--target bfdname] [--output
dirname] [--record-libdeps libdeps] [--thin] [relpos] [count] archive
[member...]
DESCRIPTION
The GNU ar program creates, modifies, and extracts from archives. An
archive is a single file holding a collection of other files in a
structure that makes it possible to retrieve the original individual
files (called members of the archive).
The original files' contents, mode (permissions), timestamp, owner, and
group are preserved in the archive, and can be restored on extraction.
GNU ar can maintain archives whose members have names of any length;
however, depending on how ar is configured on your system, a limit on
member-name length may be imposed for compatibility with archive
formats maintained with other tools. If it exists, the limit is often
15 characters (typical of formats related to a.out) or 16 characters
(typical of formats related to coff).
ar is considered a binary utility because archives of this sort are
most often used as libraries holding commonly needed subroutines.
Since libraries often will depend on other libraries, ar can also
record the dependencies of a library when the --record-libdeps option
is specified.
ar creates an index to the symbols defined in relocatable object
modules in the archive when you specify the modifier s. Once created,
this index is updated in the archive whenever ar makes a change to its
contents (save for the q update operation). An archive with such an
index speeds up linking to the library, and allows routines in the
library to call each other without regard to their placement in the
archive.
You may use nm -s or nm --print-armap to list this index table. If an
archive lacks the table, another form of ar called ranlib can be used
to add just the table.
GNU ar can optionally create a thin archive, which contains a symbol
index and references to the original copies of the member files of the
archive. This is useful for building libraries for use within a local
build tree, where the relocatable objects are expected to remain
available, and copying the contents of each object would only waste
time and space.
An archive can either be thin or it can be normal. It cannot be both
at the same time. Once an archive is created its format cannot be
changed without first deleting it and then creating a new archive in
its place.
Thin archives are also flattened, so that adding one thin archive to
another thin archive does not nest it, as would happen with a normal
archive. Instead the elements of the first archive are added
individually to the second archive.
The paths to the elements of the archive are stored relative to the
archive itself.
GNU ar is designed to be compatible with two different facilities. You
can control its activity using command-line options, like the different
varieties of ar on Unix systems; or, if you specify the single command-
line option -M, you can control it with a script supplied via standard
input, like the MRI "librarian" program.
OPTIONS
GNU ar allows you to mix the operation code p and modifier flags mod in
any order, within the first command-line argument.
If you wish, you may begin the first command-line argument with a dash.
The p keyletter specifies what operation to execute; it may be any of
the following, but you must specify only one of them:
d Delete modules from the archive. Specify the names of modules to
be deleted as member...; the archive is untouched if you specify no
files to delete.
If you specify the v modifier, ar lists each module as it is
deleted.
m Use this operation to move members in an archive.
The ordering of members in an archive can make a difference in how
programs are linked using the library, if a symbol is defined in
more than one member.
If no modifiers are used with "m", any members you name in the
member arguments are moved to the end of the archive; you can use
the a, b, or i modifiers to move them to a specified place instead.
p Print the specified members of the archive, to the standard output
file. If the v modifier is specified, show the member name before
copying its contents to standard output.
If you specify no member arguments, all the files in the archive
are printed.
q Quick append; Historically, add the files member... to the end of
archive, without checking for replacement.
The modifiers a, b, and i do not affect this operation; new members
are always placed at the end of the archive.
The modifier v makes ar list each file as it is appended.
Since the point of this operation is speed, implementations of ar
have the option of not updating the archive's symbol table if one
exists. Too many different systems however assume that symbol
tables are always up-to-date, so GNU ar will rebuild the table even
with a quick append.
Note - GNU ar treats the command qs as a synonym for r - replacing
already existing files in the archive and appending new ones at the
end.
r Insert the files member... into archive (with replacement). This
operation differs from q in that any previously existing members
are deleted if their names match those being added.
If one of the files named in member... does not exist, ar displays
an error message, and leaves undisturbed any existing members of
the archive matching that name.
By default, new members are added at the end of the file; but you
may use one of the modifiers a, b, or i to request placement
relative to some existing member.
The modifier v used with this operation elicits a line of output
for each file inserted, along with one of the letters a or r to
indicate whether the file was appended (no old member deleted) or
replaced.
s Add an index to the archive, or update it if it already exists.
Note this command is an exception to the rule that there can only
be one command letter, as it is possible to use it as either a
command or a modifier. In either case it does the same thing.
t Display a table listing the contents of archive, or those of the
files listed in member... that are present in the archive.
Normally only the member name is shown, but if the modifier O is
specified, then the corresponding offset of the member is also
displayed. Finally, in order to see the modes (permissions),
timestamp, owner, group, and size the v modifier should be
included.
If you do not specify a member, all files in the archive are
listed.
If there is more than one file with the same name (say, fie) in an
archive (say b.a), ar t b.a fie lists only the first instance; to
see them all, you must ask for a complete listing---in our example,
ar t b.a.
x Extract members (named member) from the archive. You can use the v
modifier with this operation, to request that ar list each name as
it extracts it.
If you do not specify a member, all files in the archive are
extracted.
Files cannot be extracted from a thin archive, and there are
restrictions on extracting from archives created with P: The paths
must not be absolute, may not contain "..", and any subdirectories
in the paths must exist. If it is desired to avoid these
restrictions then used the --output option to specify an output
directory.
A number of modifiers (mod) may immediately follow the p keyletter, to
specify variations on an operation's behavior:
a Add new files after an existing member of the archive. If you use
the modifier a, the name of an existing archive member must be
present as the relpos argument, before the archive specification.
b Add new files before an existing member of the archive. If you use
the modifier b, the name of an existing archive member must be
present as the relpos argument, before the archive specification.
(same as i).
c Create the archive. The specified archive is always created if it
did not exist, when you request an update. But a warning is issued
unless you specify in advance that you expect to create it, by
using this modifier.
D Operate in deterministic mode. When adding files and the archive
index use zero for UIDs, GIDs, timestamps, and use consistent file
modes for all files. When this option is used, if ar is used with
identical options and identical input files, multiple runs will
create identical output files regardless of the input files'
owners, groups, file modes, or modification times.
If binutils was configured with --enable-deterministic-archives,
then this mode is on by default. It can be disabled with the U
modifier, below.
f Truncate names in the archive. GNU ar will normally permit file
names of any length. This will cause it to create archives which
are not compatible with the native ar program on some systems. If
this is a concern, the f modifier may be used to truncate file
names when putting them in the archive.
i Insert new files before an existing member of the archive. If you
use the modifier i, the name of an existing archive member must be
present as the relpos argument, before the archive specification.
(same as b).
l Specify dependencies of this library. The dependencies must
immediately follow this option character, must use the same syntax
as the linker command line, and must be specified within a single
argument. I.e., if multiple items are needed, they must be quoted
to form a single command line argument. For example l
"-L/usr/local/lib -lmydep1 -lmydep2"
N Uses the count parameter. This is used if there are multiple
entries in the archive with the same name. Extract or delete
instance count of the given name from the archive.
o Preserve the original dates of members when extracting them. If
you do not specify this modifier, files extracted from the archive
are stamped with the time of extraction.
O Display member offsets inside the archive. Use together with the t
option.
P Use the full path name when matching or storing names in the
archive. Archives created with full path names are not POSIX
compliant, and thus may not work with tools other than up to date
GNU tools. Modifying such archives with GNU ar without using P
will remove the full path names unless the archive is a thin
archive. Note that P may be useful when adding files to a thin
archive since r without P ignores the path when choosing which
element to replace. Thus
ar rcST archive.a subdir/file1 subdir/file2 file1
will result in the first "subdir/file1" being replaced with "file1"
from the current directory. Adding P will prevent this
replacement.
s Write an object-file index into the archive, or update an existing
one, even if no other change is made to the archive. You may use
this modifier flag either with any operation, or alone. Running ar
s on an archive is equivalent to running ranlib on it.
S Do not generate an archive symbol table. This can speed up
building a large library in several steps. The resulting archive
can not be used with the linker. In order to build a symbol table,
you must omit the S modifier on the last execution of ar, or you
must run ranlib on the archive.
T Deprecated alias for --thin. T is not recommended because in many
ar implementations T has a different meaning, as specified by
X/Open System Interface.
u Normally, ar r... inserts all files listed into the archive. If
you would like to insert only those of the files you list that are
newer than existing members of the same names, use this modifier.
The u modifier is allowed only for the operation r (replace). In
particular, the combination qu is not allowed, since checking the
timestamps would lose any speed advantage from the operation q.
Note - if an archive has been created in a deterministic manner, eg
via the use of the D modifier, then replacement will always happen
and the u modifier will be ineffective.
U Do not operate in deterministic mode. This is the inverse of the D
modifier, above: added files and the archive index will get their
actual UID, GID, timestamp, and file mode values.
This is the default unless binutils was configured with
--enable-deterministic-archives.
v This modifier requests the verbose version of an operation. Many
operations display additional information, such as filenames
processed, when the modifier v is appended.
V This modifier shows the version number of ar.
The ar program also supports some command-line options which are
neither modifiers nor actions, but which do change its behaviour in
specific ways:
--help
Displays the list of command-line options supported by ar and then
exits.
--version
Displays the version information of ar and then exits.
-X32_64
ar ignores an initial option spelled -X32_64, for compatibility
with AIX. The behaviour produced by this option is the default for
GNU ar. ar does not support any of the other -X options; in
particular, it does not support -X32 which is the default for AIX
ar.
--plugin name
The optional command-line switch --plugin name causes ar to load
the plugin called name which adds support for more file formats,
including object files with link-time optimization information.
This option is only available if the toolchain has been built with
plugin support enabled.
If --plugin is not provided, but plugin support has been enabled
then ar iterates over the files in ${libdir}/bfd-plugins in
alphabetic order and the first plugin that claims the object in
question is used.
Please note that this plugin search directory is not the one used
by ld's -plugin option. In order to make ar use the linker plugin
it must be copied into the ${libdir}/bfd-plugins directory. For
GCC based compilations the linker plugin is called
liblto_plugin.so.0.0.0. For Clang based compilations it is called
LLVMgold.so. The GCC plugin is always backwards compatible with
earlier versions, so it is sufficient to just copy the newest one.
--target target
The optional command-line switch --target bfdname specifies that
the archive members are in an object code format different from
your system's default format. See
--output dirname
The --output option can be used to specify a path to a directory
into which archive members should be extracted. If this option is
not specified then the current directory will be used.
Note - although the presence of this option does imply a x
extraction operation that option must still be included on the
command line.
--record-libdeps libdeps
The --record-libdeps option is identical to the l modifier, just
handled in long form.
--thin
Make the specified archive a thin archive. If it already exists
and is a regular archive, the existing members must be present in
the same directory as archive.
@file
Read command-line options from file. The options read are inserted
in place of the original @file option. If file does not exist, or
cannot be read, then the option will be treated literally, and not
removed.
Options in file are separated by whitespace. A whitespace
character may be included in an option by surrounding the entire
option in either single or double quotes. Any character (including
a backslash) may be included by prefixing the character to be
included with a backslash. The file may itself contain additional
@file options; any such options will be processed recursively.
SEE ALSO
nm(1), ranlib(1), and the Info entries for binutils.
COPYRIGHT
Copyright (c) 1991-2025 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3 or
any later version published by the Free Software Foundation; with no
Invariant Sections, with no Front-Cover Texts, and with no Back-Cover
Texts. A copy of the license is included in the section entitled "GNU
Free Documentation License".
binutils-2.44 2025-05-12 AR(1)
C++FILT(1) Инструменты разработки GNU C++FILT(1)
NAME
c++filt - деменглинг символов C++ и Java
SYNOPSIS
c++filt [-_|--strip-underscore]
[-n|--no-strip-underscore]
[-p|--no-params]
[-t|--types]
[-i|--no-verbose]
[-r|--no-recurse-limit]
[-R|--recurse-limit]
[-s format|--format=format]
[--help] [--version] [symbol...]
DESCRIPTION
Языки C++ и Java предоставляют перегрузку функций, что означает,
что вы можете писать много функций с одним и тем же именем, при
условии, что каждая функция принимает параметры разных типов. Чтобы
различать эти функции с похожими именами, C++ и Java кодируют их
в низкоуровневое имя ассемблера, которое уникально идентифицирует
каждую версию. Этот процесс известен как mangling. Программа
c++filt [1] выполняет обратное отображение: она декодирует
(demangles) низкоуровневые имена в имена уровня пользователя,
чтобы их можно было читать.
Каждое буквенно-цифровое слово (состоящее из букв, цифр,
подчеркиваний, долларовых знаков или точек), встречающееся во
входных данных, может быть замаскированным именем. Если имя
декодируется в имя C++, то в выводе оно заменяется на имя C++,
в противном случае выводится исходное слово. Таким образом вы
можете пропустить весь исходный файл ассемблера, содержащий
замаскированные имена, через c++filt и увидеть тот же файл с
демаскированными именами.
Вы также можете использовать c++filt для расшифровки отдельных
символов, передавая их в командной строке:
c++filt <symbol>
Если аргументы символов не указаны, c++filt читает имена символов
из стандартного ввода. Все результаты выводятся в стандартный
вывод. Разница между чтением имен из командной строки и чтением
из стандартного ввода заключается в том, что аргументы командной
строки предполагаются как замаскированные имена, и не выполняется
проверка для их разделения от окружающего текста. Таким образом,
например:
c++filt -n _Z1fv
сработает и демаскирует имя в "f()", в то время как:
c++filt -n _Z1fv,
не сработает. (Обратите внимание на дополнительную запятую в конце
замаскированного имени, которая делает его недействительным).
Однако эта команда сработает:
echo _Z1fv, | c++filt -n
и выведет "f(),", то есть демаскированное имя, за которым следует
запятая. Это поведение обусловлено тем, что при чтении имен из
стандартного ввода предполагается, что они могут быть частью
файла исходного кода ассемблера, где после замаскированного имени
могут быть дополнительные, посторонние символы. Например:
.type _Z1fv, @function
OPTIONS
-_
--strip-underscore
На некоторых системах компиляторы C и C++ ставят подчеркивание
перед каждым именем. Например, имя C "foo" получает низкоуровневое
имя "_foo". Эта опция удаляет начальное подчеркивание. Удаляет ли
c++filt подчеркивание по умолчанию, зависит от цели.
-n
--no-strip-underscore
Не удалять начальное подчеркивание.
-p
--no-params
При демаскировании имени функции не отображать типы параметров
функции.
-t
--types
Пытаться демаскировать типы, а также имена функций. Это по
умолчанию отключено, поскольку замаскированные типы обычно
используются только внутри компилятора, и их можно спутать с
немаскированными именами. Например, функция под названием "a",
рассматриваемая как замаскированное имя типа, будет демаскирована
как "signed char".
-i
--no-verbose
Не включать детали реализации (если они есть) в демаскированный
вывод.
-r
--no-recurse-limit
-R
--recurse-limit
--recursion-limit
--no-recursion-limit
Включает или отключает ограничение на количество рекурсии при
демаскировании строк. Поскольку форматы маскировки имен позволяют
бесконечный уровень рекурсии, возможно создать строки, декодирование
которых исчерпает объем стека, доступного на хост-машине, вызывая
ошибку памяти. Ограничение пытается предотвратить это, ограничивая
рекурсию 2048 уровнями вложенности.
По умолчанию это ограничение включено, но его отключение может
быть необходимо для демаскирования действительно сложных имен.
Однако, если ограничение рекурсии отключено, возможно исчерпание
стека, и любые отчеты об ошибках в таком случае будут отклонены.
Опция -r является синонимом для --no-recurse-limit. Опция -R
является синонимом для --recurse-limit.
-s format
--format=format
c++filt может декодировать различные методы маскировки, используемые
разными компиляторами. Аргумент этой опции выбирает, какой метод
использовать:
"auto"
Автоматический выбор на основе исполняемого файла (метод по
умолчанию)
"gnu"
Используемый компилятором GNU C++ (g++)
"lucid"
Используемый компилятором Lucid (lcc)
"arm"
Указанный в Annotated Reference Manual C++
"hp"
Используемый компилятором HP (aCC)
"edg"
Используемый компилятором EDG
"gnu-v3"
Используемый компилятором GNU C++ (g++) с ABI V3.
"java"
Используемый компилятором GNU Java (gcj)
"gnat"
Используемый компилятором GNU Ada (GNAT).
--help
Вывести сводку опций c++filt и выйти.
--version
Вывести номер версии c++filt и выйти.
@file
Читать опции командной строки из файла. Опции, прочитанные из
файла, вставляются на место оригинальной опции @file. Если файл
не существует или не может быть прочитан, опция будет обработана
буквально, без удаления.
Опции в файле разделены пробелами. Пробельный символ может быть
включен в опцию, если вся опция окружена одинарными или двойными
кавычками. Любые символы (включая обратную косую черту) могут быть
включены, если перед ними поставить обратную косую черту. Файл
может сам содержать дополнительные опции @file; такие опции будут
обработаны рекурсивно.
FOOTNOTES
1. В MS-DOS символы "+" не допускаются в именах файлов, поэтому на
MS-DOS эта программа называется CXXFILT.
SEE ALSO
записи Info для binutils.
COPYRIGHT
Copyright (c) 1991-2025 Free Software Foundation, Inc.
Разрешается копировать, распространять и/или изменять этот документ
в соответствии с условиями Лицензии GNU Free Documentation License,
версии 1.3 или любой более поздней версии, опубликованной Free
Software Foundation; без Инвариантных Разделов, без Текстов на
Обложке и без Текстов на Задней Обложке. Копия лицензии включена в
раздел, озаглавленный "GNU Free Documentation License".
binutils-2.44 2025-05-12 C++FILT(1)
C++FILT(1) GNU Development Tools C++FILT(1)
NAME
c++filt - demangle C++ and Java symbols
SYNOPSIS
c++filt [-_|--strip-underscore]
[-n|--no-strip-underscore]
[-p|--no-params]
[-t|--types]
[-i|--no-verbose]
[-r|--no-recurse-limit]
[-R|--recurse-limit]
[-s format|--format=format]
[--help] [--version] [symbol...]
DESCRIPTION
The C++ and Java languages provide function overloading, which means
that you can write many functions with the same name, providing that
each function takes parameters of different types. In order to be able
to distinguish these similarly named functions C++ and Java encode them
into a low-level assembler name which uniquely identifies each
different version. This process is known as mangling. The c++filt [1]
program does the inverse mapping: it decodes (demangles) low-level
names into user-level names so that they can be read.
Every alphanumeric word (consisting of letters, digits, underscores,
dollars, or periods) seen in the input is a potential mangled name. If
the name decodes into a C++ name, the C++ name replaces the low-level
name in the output, otherwise the original word is output. In this way
you can pass an entire assembler source file, containing mangled names,
through c++filt and see the same source file containing demangled
names.
You can also use c++filt to decipher individual symbols by passing them
on the command line:
c++filt <symbol>
If no symbol arguments are given, c++filt reads symbol names from the
standard input instead. All the results are printed on the standard
output. The difference between reading names from the command line
versus reading names from the standard input is that command-line
arguments are expected to be just mangled names and no checking is
performed to separate them from surrounding text. Thus for example:
c++filt -n _Z1fv
will work and demangle the name to "f()" whereas:
c++filt -n _Z1fv,
will not work. (Note the extra comma at the end of the mangled name
which makes it invalid). This command however will work:
echo _Z1fv, | c++filt -n
and will display "f(),", i.e., the demangled name followed by a
trailing comma. This behaviour is because when the names are read from
the standard input it is expected that they might be part of an
assembler source file where there might be extra, extraneous characters
trailing after a mangled name. For example:
.type _Z1fv, @function
OPTIONS
-_
--strip-underscore
On some systems, both the C and C++ compilers put an underscore in
front of every name. For example, the C name "foo" gets the low-
level name "_foo". This option removes the initial underscore.
Whether c++filt removes the underscore by default is target
dependent.
-n
--no-strip-underscore
Do not remove the initial underscore.
-p
--no-params
When demangling the name of a function, do not display the types of
the function's parameters.
-t
--types
Attempt to demangle types as well as function names. This is
disabled by default since mangled types are normally only used
internally in the compiler, and they can be confused with non-
mangled names. For example, a function called "a" treated as a
mangled type name would be demangled to "signed char".
-i
--no-verbose
Do not include implementation details (if any) in the demangled
output.
-r
-R
--recurse-limit
--no-recurse-limit
--recursion-limit
--no-recursion-limit
Enables or disables a limit on the amount of recursion performed
whilst demangling strings. Since the name mangling formats allow
for an infinite level of recursion it is possible to create strings
whose decoding will exhaust the amount of stack space available on
the host machine, triggering a memory fault. The limit tries to
prevent this from happening by restricting recursion to 2048 levels
of nesting.
The default is for this limit to be enabled, but disabling it may
be necessary in order to demangle truly complicated names. Note
however that if the recursion limit is disabled then stack
exhaustion is possible and any bug reports about such an event will
be rejected.
The -r option is a synonym for the --no-recurse-limit option. The
-R option is a synonym for the --recurse-limit option.
-s format
--format=format
c++filt can decode various methods of mangling, used by different
compilers. The argument to this option selects which method it
uses:
"auto"
Automatic selection based on executable (the default method)
"gnu"
the one used by the GNU C++ compiler (g++)
"lucid"
the one used by the Lucid compiler (lcc)
"arm"
the one specified by the C++ Annotated Reference Manual
"hp"
the one used by the HP compiler (aCC)
"edg"
the one used by the EDG compiler
"gnu-v3"
the one used by the GNU C++ compiler (g++) with the V3 ABI.
"java"
the one used by the GNU Java compiler (gcj)
"gnat"
the one used by the GNU Ada compiler (GNAT).
--help
Print a summary of the options to c++filt and exit.
--version
Print the version number of c++filt and exit.
@file
Read command-line options from file. The options read are inserted
in place of the original @file option. If file does not exist, or
cannot be read, then the option will be treated literally, and not
removed.
Options in file are separated by whitespace. A whitespace
character may be included in an option by surrounding the entire
option in either single or double quotes. Any character (including
a backslash) may be included by prefixing the character to be
included with a backslash. The file may itself contain additional
@file options; any such options will be processed recursively.
FOOTNOTES
1. MS-DOS does not allow "+" characters in file names, so on MS-DOS
this program is named CXXFILT.
SEE ALSO
the Info entries for binutils.
COPYRIGHT
Copyright (c) 1991-2025 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3 or
any later version published by the Free Software Foundation; with no
Invariant Sections, with no Front-Cover Texts, and with no Back-Cover
Texts. A copy of the license is included in the section entitled "GNU
Free Documentation License".
binutils-2.44 2025-05-12 C++FILT(1)
WINDRES(1) Инструменты разработки GNU WINDRES(1)
NAME
windres - манипулирование ресурсами Windows
SYNOPSIS
windres [options] [input-file] [output-file]
DESCRIPTION
windres читает ресурсы из входного файла и копирует их в выходной файл. Каждый файл может быть в одном из трёх форматов:
"rc"
Текстовый формат, читаемый Компилятором Ресурсов.
"res"
Двоичный формат, генерируемый Компилятором Ресурсов.
"coff"
COFF-объект или исполняемый файл.
Точное описание этих различных форматов доступно в документации от Microsoft.
Когда windres преобразует из формата "rc" в формат "res", он действует как Компилятор Ресурсов Windows. Когда windres преобразует из формата "res" в формат "coff", он действует как программа Windows "CVTRES".
Когда windres генерирует файл "rc", вывод похож, но не идентичен формату, ожидаемому для входа. Когда входной файл "rc" ссылается на внешнее имя файла, выходной файл "rc" вместо этого включит содержимое файла.
Если формат входа или выхода не указан, windres угадает на основе имени файла или, для входного файла, содержимого файла. Файл с расширением .rc будет рассматриваться как файл "rc", файл с расширением .res будет рассматриваться как файл "res", а файл с расширением .o или .exe будет рассматриваться как файл "coff".
Если выходной файл не указан, windres выведет ресурсы в формате "rc" в стандартный вывод.
Обычное использование заключается в том, чтобы написать файл "rc", использовать windres для преобразования его в файл COFF-объекта, а затем связать файл COFF с вашим приложением. Это сделает ресурсы, описанные в файле "rc", доступными для Windows.
OPTIONS
-i filename
--input filename
Имя входного файла. Если эта опция не используется, то windres использует первый аргумент, не являющийся опцией, как имя входного файла. Если нет аргументов, не являющихся опциями, то windres будет читать из стандартного ввода. windres не может читать файл COFF из стандартного ввода.
-o filename
--output filename
Имя выходного файла. Если эта опция не используется, то windres использует первый аргумент, не являющийся опцией, после любого, использованного для имени входного файла, как имя выходного файла. Если нет аргументов, не являющихся опциями, то windres будет писать в стандартный вывод. windres не может писать файл COFF в стандартный вывод. Обратите внимание, для совместимости с rc опция -fo также принимается, но её использование не рекомендуется.
-J format
--input-format format
Формат входа для чтения. format может быть res, rc или coff. Если формат входа не указан, windres угадает, как описано выше.
-O format
--output-format format
Формат выхода для генерации. format может быть res, rc или coff. Если формат выхода не указан, windres угадает, как описано выше.
-F target
--target target
Укажите формат BFD для использования с файлом COFF как входом или выходом. Это имя цели BFD; вы можете использовать опцию --help, чтобы увидеть список поддерживаемых целей. Нормально windres использует формат по умолчанию, который является первым в списке, выводимом опцией --help.
--preprocessor program
Когда windres читает файл "rc", он сначала пропускает его через препроцессор C. Эта опция может быть использована для указания препроцессора. Препроцессор по умолчанию - "gcc".
--preprocessor-arg option
Когда windres читает файл "rc", он сначала пропускает его через препроцессор C. Эта опция может быть использована для указания дополнительного текста, передаваемого препроцессору в его командной строке. Эта опция может быть использована несколько раз для добавления нескольких опций в командную строку препроцессора. Если опция --preprocessor не указана, то будет использован набор опций препроцессора по умолчанию, с любыми опциями --preprocessor-arg, размещаемыми после них на командной строке. Эти опции по умолчанию - "-E", "-xc-header" и "-DRC_INVOKED".
-I directory
--include-dir directory
Укажите каталог включений для использования при чтении файла "rc". windres передаст это препроцессору как опцию -I. windres также будет искать в этом каталоге при поиске файлов, указанных в файле "rc". Если аргумент, переданный этой команде, соответствует одному из поддерживаемых форматов (как описано в опции -J), будет выдано предупреждение об устаревшем использовании, и поведение будет таким же, как у опции -J. Новые программы не должны использовать это поведение. Если каталог совпадает с форматом, просто добавьте перед ним ./, чтобы отключить обратную совместимость.
-D target
--define sym[=val]
Укажите опцию -D для передачи препроцессору при чтении файла "rc".
-U target
--undefine sym
Укажите опцию -U для передачи препроцессору при чтении файла "rc".
-r Игнорируется для совместимости с rc.
-v Включить режим подробного вывода. Это сообщит вам, какой препроцессор используется, если вы его не указали.
-c val
--codepage val
Укажите кодовую страницу по умолчанию для использования при чтении файла "rc". val должен быть шестнадцатеричным числом, начинающимся с 0x, или десятичным кодом кодовой страницы. Допустимый диапазон - от нуля до 0xffff, но допустимость кодовой страницы зависит от хоста и конфигурации.
-l val
--language val
Укажите язык по умолчанию для использования при чтении файла "rc". val должен быть шестнадцатеричным кодом языка. Нижние восемь бит - это язык, а верхние восемь бит - подязык.
--use-temp-file
Использовать временный файл вместо popen для чтения вывода препроцессора. Используйте эту опцию, если реализация popen на хосте имеет ошибки (например, в определённых неанглийских версиях Windows 95 и Windows 98 известно, что popen имеет ошибки, где вывод вместо этого уходит в консоль).
--no-use-temp-file
Использовать popen, а не временный файл, для чтения вывода препроцессора. Это поведение по умолчанию.
-h
--help
Выводит сводку использования.
-V
--version
Выводит номер версии windres.
--yydebug
Если windres скомпилирован с "YYDEBUG", определённым как 1, это включит отладку парсера.
@file
Читать опции командной строки из файла. Прочитанные опции вставляются на место оригинальной опции @file. Если файл не существует или не может быть прочитан, опция будет обработана буквально, без удаления.
Опции в файле разделяются пробелами. Пробельный символ может быть включён в опцию, если окружить всю опцию в одинарные или двойные кавычки. Любые символы (включая обратную косую черту) могут быть включены путём добавления перед ними обратной косой черты. Файл может сам содержать дополнительные опции @file; такие опции будут обработаны рекурсивно.
SEE ALSO
записи Info для binutils.
COPYRIGHT
Copyright (c) 1991-2025 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3 or
any later version published by the Free Software Foundation; with no
Invariant Sections, with no Front-Cover Texts, and with no Back-Cover
Texts. A copy of the license is included in the section entitled "GNU
Free Documentation License".
binutils-2.44 2025-05-12 WINDRES(1)
WINDRES(1) GNU Development Tools WINDRES(1)
NAME
windres - manipulate Windows resources
SYNOPSIS
windres [options] [input-file] [output-file]
DESCRIPTION
windres reads resources from an input file and copies them into an
output file. Either file may be in one of three formats:
"rc"
A text format read by the Resource Compiler.
"res"
A binary format generated by the Resource Compiler.
"coff"
A COFF object or executable.
The exact description of these different formats is available in
documentation from Microsoft.
When windres converts from the "rc" format to the "res" format, it is
acting like the Windows Resource Compiler. When windres converts from
the "res" format to the "coff" format, it is acting like the Windows
"CVTRES" program.
When windres generates an "rc" file, the output is similar but not
identical to the format expected for the input. When an input "rc"
file refers to an external filename, an output "rc" file will instead
include the file contents.
If the input or output format is not specified, windres will guess
based on the file name, or, for the input file, the file contents. A
file with an extension of .rc will be treated as an "rc" file, a file
with an extension of .res will be treated as a "res" file, and a file
with an extension of .o or .exe will be treated as a "coff" file.
If no output file is specified, windres will print the resources in
"rc" format to standard output.
The normal use is for you to write an "rc" file, use windres to convert
it to a COFF object file, and then link the COFF file into your
application. This will make the resources described in the "rc" file
available to Windows.
OPTIONS
-i filename
--input filename
The name of the input file. If this option is not used, then
windres will use the first non-option argument as the input file
name. If there are no non-option arguments, then windres will read
from standard input. windres can not read a COFF file from
standard input.
-o filename
--output filename
The name of the output file. If this option is not used, then
windres will use the first non-option argument, after any used for
the input file name, as the output file name. If there is no non-
option argument, then windres will write to standard output.
windres can not write a COFF file to standard output. Note, for
compatibility with rc the option -fo is also accepted, but its use
is not recommended.
-J format
--input-format format
The input format to read. format may be res, rc, or coff. If no
input format is specified, windres will guess, as described above.
-O format
--output-format format
The output format to generate. format may be res, rc, or coff. If
no output format is specified, windres will guess, as described
above.
-F target
--target target
Specify the BFD format to use for a COFF file as input or output.
This is a BFD target name; you can use the --help option to see a
list of supported targets. Normally windres will use the default
format, which is the first one listed by the --help option.
--preprocessor program
When windres reads an "rc" file, it runs it through the C
preprocessor first. This option may be used to specify the
preprocessor to use. The default preprocessor is "gcc".
--preprocessor-arg option
When windres reads an "rc" file, it runs it through the C
preprocessor first. This option may be used to specify additional
text to be passed to preprocessor on its command line. This option
can be used multiple times to add multiple options to the
preprocessor command line. If the --preprocessor option has not
been specified then a default set of preprocessor arguments will be
used, with any --preprocessor-arg options being placed after them
on the command line. These default arguments are "-E",
"-xc-header" and "-DRC_INVOKED".
-I directory
--include-dir directory
Specify an include directory to use when reading an "rc" file.
windres will pass this to the preprocessor as an -I option.
windres will also search this directory when looking for files
named in the "rc" file. If the argument passed to this command
matches any of the supported formats (as described in the -J
option), it will issue a deprecation warning, and behave just like
the -J option. New programs should not use this behaviour. If a
directory happens to match a format, simple prefix it with ./ to
disable the backward compatibility.
-D target
--define sym[=val]
Specify a -D option to pass to the preprocessor when reading an
"rc" file.
-U target
--undefine sym
Specify a -U option to pass to the preprocessor when reading an
"rc" file.
-r Ignored for compatibility with rc.
-v Enable verbose mode. This tells you what the preprocessor is if
you didn't specify one.
-c val
--codepage val
Specify the default codepage to use when reading an "rc" file. val
should be a hexadecimal prefixed by 0x or decimal codepage code.
The valid range is from zero up to 0xffff, but the validity of the
codepage is host and configuration dependent.
-l val
--language val
Specify the default language to use when reading an "rc" file. val
should be a hexadecimal language code. The low eight bits are the
language, and the high eight bits are the sublanguage.
--use-temp-file
Use a temporary file to instead of using popen to read the output
of the preprocessor. Use this option if the popen implementation is
buggy on the host (eg., certain non-English language versions of
Windows 95 and Windows 98 are known to have buggy popen where the
output will instead go the console).
--no-use-temp-file
Use popen, not a temporary file, to read the output of the
preprocessor. This is the default behaviour.
-h
--help
Prints a usage summary.
-V
--version
Prints the version number for windres.
--yydebug
If windres is compiled with "YYDEBUG" defined as 1, this will turn
on parser debugging.
@file
Read command-line options from file. The options read are inserted
in place of the original @file option. If file does not exist, or
cannot be read, then the option will be treated literally, and not
removed.
Options in file are separated by whitespace. A whitespace
character may be included in an option by surrounding the entire
option in either single or double quotes. Any character (including
a backslash) may be included by prefixing the character to be
included with a backslash. The file may itself contain additional
@file options; any such options will be processed recursively.
SEE ALSO
the Info entries for binutils.
COPYRIGHT
Copyright (c) 1991-2025 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3 or
any later version published by the Free Software Foundation; with no
Invariant Sections, with no Front-Cover Texts, and with no Back-Cover
Texts. A copy of the license is included in the section entitled "GNU
Free Documentation License".
binutils-2.44 2025-05-12 WINDRES(1)
STRIP(1) Инструменты разработки GNU STRIP(1)
NAME
strip - удаление символов и других данных из объектных файлов
SYNOPSIS
strip [-F bfdname |--target=bfdname]
[-I bfdname |--input-target=bfdname]
[-O bfdname |--output-target=bfdname]
[-s|--strip-all]
[-S|-g|-d|--strip-debug]
[--strip-dwo]
[-K symbolname|--keep-symbol=symbolname]
[-M|--merge-notes][--no-merge-notes]
[-N symbolname |--strip-symbol=symbolname]
[-w|--wildcard]
[-x|--discard-all] [-X |--discard-locals]
[-R sectionname |--remove-section=sectionname]
[--keep-section=sectionpattern]
[--remove-relocations=sectionpattern]
[--strip-section-headers]
[-o file] [-p|--preserve-dates]
[-D|--enable-deterministic-archives]
[-U|--disable-deterministic-archives]
[--keep-section-symbols]
[--keep-file-symbols]
[--only-keep-debug]
[-v |--verbose] [-V|--version]
[--help] [--info]
objfile...
DESCRIPTION
Программа GNU strip удаляет все символы из объектных файлов objfile. Список
объектных файлов может включать архивы. Должен быть указан хотя бы один
объектный файл.
strip модифицирует файлы, указанные в аргументах, а не создаёт
модифицированные копии под другими именами.
OPTIONS
-F bfdname
--target=bfdname
Рассматривать исходный objfile как файл с форматом объектного кода
bfdname и перезаписывать его в том же формате.
--help
Показать сводку опций для strip и выйти.
--info
Вывести список всех доступных архитектур и форматов объектных файлов.
-I bfdname
--input-target=bfdname
Рассматривать исходный objfile как файл с форматом объектного кода
bfdname.
-O bfdname
--output-target=bfdname
Заменить objfile файлом в формате вывода bfdname.
-R sectionname
--remove-section=sectionname
Удалить любой раздел с именем sectionname из выходного файла, в
дополнение к разделам, которые иначе были бы удалены. Эта опция может
быть указана несколько раз. Обратите внимание, что использование этой
опции неподходящим образом может сделать выходной файл непригодным к
использованию. Символ подстановки * может быть указан в конце
sectionname. В этом случае будут удалены все разделы, начинающиеся с
sectionname.
Если первый символ sectionpattern — восклицательный знак (!) то
соответствующие разделы не будут удалены, даже если более раннее
использование --remove-section в той же командной строке могло бы
удалить их. Например:
--remove-section=.text.* --remove-section=!.text.foo
удалит все разделы, соответствующие шаблону '.text.*', но не удалит
раздел '.text.foo'.
--keep-section=sectionpattern
При удалении разделов из выходного файла сохранять разделы, которые
соответствуют sectionpattern.
--remove-relocations=sectionpattern
Удалить релокации из выходного файла для любого раздела, соответствующего
sectionpattern. Эта опция может быть указана несколько раз. Обратите
внимание, что использование этой опции неподходящим образом может сделать
выходной файл непригодным к использованию. Символы подстановки
принимаются в sectionpattern. Например:
--remove-relocations=.text.*
удалит релокации для всех разделов, соответствующих шаблону
'.text.*'.
Если первый символ sectionpattern — восклицательный знак (!) то
релокации для соответствующих разделов не будут удалены, даже если
более раннее использование --remove-relocations в той же командной
строке могло бы удалить их. Например:
--remove-relocations=.text.* --remove-relocations=!.text.foo
удалит все релокации для разделов, соответствующих шаблону
'.text.*', но не удалит релокации для раздела '.text.foo'.
--strip-section-headers
Удалить заголовки разделов. Эта опция специфична для файлов ELF.
Подразумевает --strip-all и --merge-notes.
-s
--strip-all
Удалить все символы.
-g
-S
-d
--strip-debug
Удалить только отладочные символы.
--strip-dwo
Удалить содержимое всех разделов DWARF .dwo, оставив остальные
отладочные разделы и все символы нетронутыми. См. описание этой опции
в разделе objcopy для дополнительной информации.
--strip-unneeded
Удалить все символы, которые не нужны для обработки релокаций, в
дополнение к отладочным символам и разделам, удаляемым с помощью
--strip-debug.
-K symbolname
--keep-symbol=symbolname
При удалении символов сохранять символ symbolname, даже если он
обычно был бы удалён. Эта опция может быть указана несколько раз.
-M
--merge-notes
--no-merge-notes
Для файлов ELF попытаться (или не попытаться) уменьшить размер
разделов типа SHT_NOTE, удаляя дублирующиеся заметки. По умолчанию
эта оптимизация выполняется, если не удаляется отладочная информация
или информация DWO.
-N symbolname
--strip-symbol=symbolname
Удалить символ symbolname из исходного файла. Эта опция может быть
указана несколько раз и может быть объединена с опциями strip,
отличными от -K.
-o file
Поместить очищенный вывод в file, вместо замены существующего
файла. При использовании этого аргумента может быть указан только
один аргумент objfile.
-p
--preserve-dates
Сохранить даты доступа и модификации файла.
-D
--enable-deterministic-archives
Работать в детерминированном режиме. При копировании членов архива
и записи индекса архива использовать ноль для UID, GID, меток времени
и последовательных режимов файлов для всех файлов.
Если binutils был настроен с --enable-deterministic-archives, то
этот режим включён по умолчанию. Его можно отключить с помощью
опции -U, ниже.
-U
--disable-deterministic-archives
Не работать в детерминированном режиме. Это противоположность
опции -D: при копировании членов архива и записи индекса архива
использовать их фактические значения UID, GID, меток времени и
режимов файлов.
Это значение по умолчанию, если binutils был настроен с
--enable-deterministic-archives.
-w
--wildcard
Разрешить регулярные выражения в именах символов, используемых в
других опциях командной строки. Символы подстановки вопросительный
знак (?), звёздочка (*), обратная косая черта (\) и квадратные
скобки ([]) могут быть использованы в любом месте имени символа.
Если первый символ имени символа — восклицательный знак (!) то
смысл переключателя инвертируется для этого символа. Например:
-w -K !foo -K fo*
заставит strip сохранять только символы, начинающиеся с букв
"fo", но удалить символ "foo".
-x
--discard-all
Удалить не глобальные символы.
-X
--discard-locals
Удалить локальные символы, генерируемые компилятором. (Они обычно
начинаются с L или ..)
--keep-section-symbols
При очистке файла, возможно с --strip-debug или --strip-unneeded,
сохранять любые символы, указывающие имена разделов, которые
иначе были бы удалены.
--keep-file-symbols
При очистке файла, возможно с --strip-debug или --strip-unneeded,
сохранять любые символы, указывающие имена исходных файлов, которые
иначе были бы удалены.
--only-keep-debug
Очистить файл, опустошив содержимое любых разделов, которые не
были бы удалены с помощью --strip-debug, и оставить отладочные
разделы нетронутыми. В файлах ELF это также сохраняет все разделы
заметок в выводе.
Обратите внимание — заголовки разделов очищенных разделов
сохраняются, включая их размеры, но содержимое разделов
отбрасывается. Заголовки разделов сохраняются, чтобы другие
инструлы могли сопоставить файл с отладочной информацией с
реальным исполняемым файлом, даже если этот файл был перемещён в
другое адресное пространство.
Цель — использовать эту опцию вместе с --add-gnu-debuglink для
создания двухкомпонентного исполняемого файла. Один — очищенный
бинарный файл, который будет занимать меньше места в ОЗУ и в
дистрибуции, а второй — файл с отладочной информацией, который
нужен только если требуется отладка. Предлагаемая процедура
создания этих файлов следующая:
1.<Слинкуйте исполняемый файл как обычно. Предполагая, что он называется>
"foo" тогда...
1.<Выполните "objcopy --only-keep-debug foo foo.dbg", чтобы>
создать файл, содержащий отладочную информацию.
1.<Выполните "objcopy --strip-debug foo", чтобы создать>
очищенный исполняемый файл.
1.<Выполните "objcopy --add-gnu-debuglink=foo.dbg foo">
чтобы добавить ссылку на отладочную информацию в очищенный
исполняемый файл.
Обратите внимание — выбор расширения ".dbg" для файла с
отладочной информацией произвольный. Также шаг "--only-keep-debug"
необязательный. Вы могли бы сделать это так:
1.<Слинкуйте исполняемый файл как обычно.>
1.<Скопируйте "foo" в "foo.full">
1.<Выполните "strip --strip-debug foo">
1.<Выполните "objcopy --add-gnu-debuglink=foo.full foo">
т.е., файл, на который указывает --add-gnu-debuglink, может быть
полным исполняемым файлом. Он не обязательно должен быть файлом,
созданным с помощью переключателя --only-keep-debug.
Обратите внимание — этот переключатель предназначен только для
использования с полностью слинкованными файлами. Не имеет смысла
использовать его для объектных файлов, где отладочная информация
может быть неполной. Кроме того, функция gnu_debuglink в настоящее
время поддерживает только наличие одного имени файла с
отладочной информацией, а не несколько имён на основе одного файла
на объект.
-V
--version
Показать номер версии strip.
-v
--verbose
Подробный вывод: перечислить все модифицированные объектные файлы. В
случае архивов strip -v перечисляет все члены архива.
@file
Читать опции командной строки из file. Прочитанные опции вставляются
на место оригинальной опции @file. Если file не существует или не
может быть прочитан, опция будет обработана буквально, без удаления.
Опции в file разделены пробелами. Символ пробела может быть включён
в опцию путём заключения всей опции в одинарные или двойные кавычки.
Любые символы (включая обратную косую черту) могут быть включены путём
добавления перед ними обратной косой черты. Файл может сам содержать
дополнительные опции @file; любые такие опции будут обработаны
рекурсивно.
SEE ALSO
разделы Info для binutils.
COPYRIGHT
Copyright (c) 1991-2025 Free Software Foundation, Inc.
Разрешается копировать, распространять и/или модифицировать этот документ
в соответствии с условиями Лицензии GNU Free Documentation License,
версии 1.3 или любой более поздней версии, опубликованной Free Software
Foundation; без Инвариантных Разделов, без Текстов на Обложке и без
Текстов на Задней Обложке. Копия лицензии включена в раздел, озаглавленный
"GNU Free Documentation License".
binutils-2.44 2025-05-12 STRIP(1)
STRIP(1) GNU Development Tools STRIP(1)
NAME
strip - discard symbols and other data from object files
SYNOPSIS
strip [-F bfdname |--target=bfdname]
[-I bfdname |--input-target=bfdname]
[-O bfdname |--output-target=bfdname]
[-s|--strip-all]
[-S|-g|-d|--strip-debug]
[--strip-dwo]
[-K symbolname|--keep-symbol=symbolname]
[-M|--merge-notes][--no-merge-notes]
[-N symbolname |--strip-symbol=symbolname]
[-w|--wildcard]
[-x|--discard-all] [-X |--discard-locals]
[-R sectionname |--remove-section=sectionname]
[--keep-section=sectionpattern]
[--remove-relocations=sectionpattern]
[--strip-section-headers]
[-o file] [-p|--preserve-dates]
[-D|--enable-deterministic-archives]
[-U|--disable-deterministic-archives]
[--keep-section-symbols]
[--keep-file-symbols]
[--only-keep-debug]
[-v |--verbose] [-V|--version]
[--help] [--info]
objfile...
DESCRIPTION
GNU strip discards all symbols from object files objfile. The list of
object files may include archives. At least one object file must be
given.
strip modifies the files named in its argument, rather than writing
modified copies under different names.
OPTIONS
-F bfdname
--target=bfdname
Treat the original objfile as a file with the object code format
bfdname, and rewrite it in the same format.
--help
Show a summary of the options to strip and exit.
--info
Display a list showing all architectures and object formats
available.
-I bfdname
--input-target=bfdname
Treat the original objfile as a file with the object code format
bfdname.
-O bfdname
--output-target=bfdname
Replace objfile with a file in the output format bfdname.
-R sectionname
--remove-section=sectionname
Remove any section named sectionname from the output file, in
addition to whatever sections would otherwise be removed. This
option may be given more than once. Note that using this option
inappropriately may make the output file unusable. The wildcard
character * may be given at the end of sectionname. If so, then
any section starting with sectionname will be removed.
If the first character of sectionpattern is the exclamation point
(!) then matching sections will not be removed even if an earlier
use of --remove-section on the same command line would otherwise
remove it. For example:
--remove-section=.text.* --remove-section=!.text.foo
will remove all sections matching the pattern '.text.*', but will
not remove the section '.text.foo'.
--keep-section=sectionpattern
When removing sections from the output file, keep sections that
match sectionpattern.
--remove-relocations=sectionpattern
Remove relocations from the output file for any section matching
sectionpattern. This option may be given more than once. Note
that using this option inappropriately may make the output file
unusable. Wildcard characters are accepted in sectionpattern. For
example:
--remove-relocations=.text.*
will remove the relocations for all sections matching the patter
'.text.*'.
If the first character of sectionpattern is the exclamation point
(!) then matching sections will not have their relocation removed
even if an earlier use of --remove-relocations on the same command
line would otherwise cause the relocations to be removed. For
example:
--remove-relocations=.text.* --remove-relocations=!.text.foo
will remove all relocations for sections matching the pattern
'.text.*', but will not remove relocations for the section
'.text.foo'.
--strip-section-headers
Strip section headers. This option is specific to ELF files.
Implies --strip-all and --merge-notes.
-s
--strip-all
Remove all symbols.
-g
-S
-d
--strip-debug
Remove debugging symbols only.
--strip-dwo
Remove the contents of all DWARF .dwo sections, leaving the
remaining debugging sections and all symbols intact. See the
description of this option in the objcopy section for more
information.
--strip-unneeded
Remove all symbols that are not needed for relocation processing in
addition to debugging symbols and sections stripped by
--strip-debug.
-K symbolname
--keep-symbol=symbolname
When stripping symbols, keep symbol symbolname even if it would
normally be stripped. This option may be given more than once.
-M
--merge-notes
--no-merge-notes
For ELF files, attempt (or do not attempt) to reduce the size of
any SHT_NOTE type sections by removing duplicate notes. The
default is to attempt this reduction unless stripping debug or DWO
information.
-N symbolname
--strip-symbol=symbolname
Remove symbol symbolname from the source file. This option may be
given more than once, and may be combined with strip options other
than -K.
-o file
Put the stripped output in file, rather than replacing the existing
file. When this argument is used, only one objfile argument may be
specified.
-p
--preserve-dates
Preserve the access and modification dates of the file.
-D
--enable-deterministic-archives
Operate in deterministic mode. When copying archive members and
writing the archive index, use zero for UIDs, GIDs, timestamps, and
use consistent file modes for all files.
If binutils was configured with --enable-deterministic-archives,
then this mode is on by default. It can be disabled with the -U
option, below.
-U
--disable-deterministic-archives
Do not operate in deterministic mode. This is the inverse of the
-D option, above: when copying archive members and writing the
archive index, use their actual UID, GID, timestamp, and file mode
values.
This is the default unless binutils was configured with
--enable-deterministic-archives.
-w
--wildcard
Permit regular expressions in symbolnames used in other command
line options. The question mark (?), asterisk (*), backslash (\)
and square brackets ([]) operators can be used anywhere in the
symbol name. If the first character of the symbol name is the
exclamation point (!) then the sense of the switch is reversed for
that symbol. For example:
-w -K !foo -K fo*
would cause strip to only keep symbols that start with the letters
"fo", but to discard the symbol "foo".
-x
--discard-all
Remove non-global symbols.
-X
--discard-locals
Remove compiler-generated local symbols. (These usually start with
L or ..)
--keep-section-symbols
When stripping a file, perhaps with --strip-debug or
--strip-unneeded, retain any symbols specifying section names,
which would otherwise get stripped.
--keep-file-symbols
When stripping a file, perhaps with --strip-debug or
--strip-unneeded, retain any symbols specifying source file names,
which would otherwise get stripped.
--only-keep-debug
Strip a file, emptying the contents of any sections that would not
be stripped by --strip-debug and leaving the debugging sections
intact. In ELF files, this preserves all the note sections in the
output as well.
Note - the section headers of the stripped sections are preserved,
including their sizes, but the contents of the section are
discarded. The section headers are preserved so that other tools
can match up the debuginfo file with the real executable, even if
that executable has been relocated to a different address space.
The intention is that this option will be used in conjunction with
--add-gnu-debuglink to create a two part executable. One a
stripped binary which will occupy less space in RAM and in a
distribution and the second a debugging information file which is
only needed if debugging abilities are required. The suggested
procedure to create these files is as follows:
1.<Link the executable as normal. Assuming that it is called>
"foo" then...
1.<Run "objcopy --only-keep-debug foo foo.dbg" to>
create a file containing the debugging info.
1.<Run "objcopy --strip-debug foo" to create a>
stripped executable.
1.<Run "objcopy --add-gnu-debuglink=foo.dbg foo">
to add a link to the debugging info into the stripped
executable.
Note---the choice of ".dbg" as an extension for the debug info file
is arbitrary. Also the "--only-keep-debug" step is optional. You
could instead do this:
1.<Link the executable as normal.>
1.<Copy "foo" to "foo.full">
1.<Run "strip --strip-debug foo">
1.<Run "objcopy --add-gnu-debuglink=foo.full foo">
i.e., the file pointed to by the --add-gnu-debuglink can be the
full executable. It does not have to be a file created by the
--only-keep-debug switch.
Note---this switch is only intended for use on fully linked files.
It does not make sense to use it on object files where the
debugging information may be incomplete. Besides the gnu_debuglink
feature currently only supports the presence of one filename
containing debugging information, not multiple filenames on a one-
per-object-file basis.
-V
--version
Show the version number for strip.
-v
--verbose
Verbose output: list all object files modified. In the case of
archives, strip -v lists all members of the archive.
@file
Read command-line options from file. The options read are inserted
in place of the original @file option. If file does not exist, or
cannot be read, then the option will be treated literally, and not
removed.
Options in file are separated by whitespace. A whitespace
character may be included in an option by surrounding the entire
option in either single or double quotes. Any character (including
a backslash) may be included by prefixing the character to be
included with a backslash. The file may itself contain additional
@file options; any such options will be processed recursively.
SEE ALSO
the Info entries for binutils.
COPYRIGHT
Copyright (c) 1991-2025 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3 or
any later version published by the Free Software Foundation; with no
Invariant Sections, with no Front-Cover Texts, and with no Back-Cover
Texts. A copy of the license is included in the section entitled "GNU
Free Documentation License".
binutils-2.44 2025-05-12 STRIP(1)
GPROFNG-ARCHIVE(1) Команды пользователя GPROFNG-ARCHIVE(1)
NAME
gprofng-archive - Архивация данных эксперимента gprofng
SYNOPSIS
gprofng archive [option(s)] experiment
DESCRIPTION
Архивация связанных бинарных файлов приложения и исходных файлов в
эксперименте gprofng для создания самодостаточного и переносимого
эксперимента.
По умолчанию бинарные файлы архивируются в процессе сбора данных,
но исходные файлы приложения не архивируются. Используйте этот
инструмент для изменения этого поведения и последующей архивации
дополнительных компонентов.
Этот инструмент должен выполняться на той же системе, где были
записаны данные профилирования.
OPTIONS
--version
Вывести номер версии и выйти.
--help
Вывести информацию об использовании и выйти.
-a {off | on | ldobjects | src | usedldobjects | used[src]}
Указать архивацию бинарных файлов и других файлов. Помимо
отключения этой функции (off) или включения архивации всех
loadobjects и исходных файлов (on), другие варианты поддерживают
более точный выбор.
Все эти варианты включают архивацию, но ключевое слово управляет
тем, что именно выбрано: все load objects (ldobjects), все исходные
файлы (src), loadobjects, связанные с программным счётчиком
(usedldobjects), или исходные файлы, связанные с программным
счётчиком (used[src]). По умолчанию используется -a ldobjects.
-d path
Путь — это абсолютный путь к общему архиву, который является
каталогом, содержащим архивированные файлы. Если каталог не
существует, он будет создан. Файлы сохраняются в каталоге общего
архива, и в архиве эксперимента создаётся символическая ссылка.
-F Принудительное выполнение записи или перезаписи файлов .archive.
Все архивированные файлы будут удалены и пересозданы, за
исключением случаев, когда используются опции -n или -m, или если
эксперимент является подэкспериментом.
-m regex
Архивировать только те исходные, объектные и файлы отладочной
информации, полное имя пути которых соответствует данной
регулярному выражению POSIX.
-n Архивировать только указанный эксперимент, не архивируя его
потомков.
-q Не выводить никаких предупреждений в stderr. Предупреждения
включаются в файл .archive в каталоге эксперимента. Они отображаются
в выводе команды gprofng display text.
-r path
Эта опция указывает местоположение общего архива. Значение —
относительный путь к общему архиву, который является каталогом,
содержащим архивированные файлы. Если каталог не существует, он
будет создан. Файлы сохраняются в каталоге общего архива, и в
архиве эксперимента создаётся символическая ссылка.
-s selection
Указать архивацию исходных файлов. Допустимые значения для
selection:
no Не архивировать никаких исходных файлов.
all Архивировать все исходные и объектные файлы, которые можно
найти.
used[src]
Архивировать исходные и объектные файлы для функций, против
которых были записаны данные в эксперименте, и которые можно
найти.
По умолчанию исходные файлы приложения не архивируются в
эксперимент. Если используются опции -s all или -s used, исходные
и объектные файлы архивируются. Эти опции также обеспечивают
наличие исходных файлов в эксперименте, даже если оригинальные
исходные файлы были изменены или стали недоступны.
В случае, если архивируемые файлы не удаётся найти, используйте
команды addpath или pathmap, или обе, в файле .er.rc для указания
местоположения отсутствующих файлов.
NOTES
- Архивация бинарных файлов приложения — По умолчанию бинарные
файлы архивируются автоматически при создании эксперимента.
Однако архивация не происходит в одном или нескольких из
следующих случаев:
• Если профилируемое приложение завершается до нормального
выхода.
• Если профилируется запущенный процесс.
• Если архивация явно отключена при профилировании. Например,
с помощью опции -a off в gprofng collect app.
В этих случаях gprofng archive нужно запускать вручную и на той же
машине, где были записаны данные профилирования.
Архивация данных эксперимента во время процесса сбора данных может
быть довольно затратной. Особенно если эксперимент имеет много
потомков процессов. В таких случаях более эффективная стратегия —
использовать опцию -a off при сборе данных. После завершения
сбора данных можно архивировать с помощью опции -s all. Это
сохранит все исполняемые файлы и исходные файлы в эксперименте.
Если во время архивации появляется сообщение об ошибке, что
исполняемый файл или исходный файл не найден, команду addpath для
добавления пути к отсутствующим файлам можно включить в файл
.er.rc. После добавления этой команды снова архивируйте
эксперимент. Архивацию можно повторять столько раз, сколько
необходимо, чтобы архивировать все файлы.
Архивацию следует выполнять на той же системе, которая использовалась
для сбора эксперимента. Если некоторые файлы недоступны с этой
системы (например, исходные или объектные файлы), то дополнительную
архивацию можно выполнить с помощью другой системы, которая имеет к
ним доступ. Например, системы, где приложение было построено.
Некоторые приложения Java хранят разделяемые объекты в файлах jar.
По умолчанию такие разделяемые объекты не архивируются
автоматически. Чтобы архивировать разделяемые объекты, содержащиеся
в файлах jar, убедитесь, что команда addpath включена в файл
.er.rc. Команда addpath должна указывать путь к файлу jar,
включая сам файл jar. Файл .er.rc должен быть сохранён в домашнем
каталоге пользователя или в каталоге родителя эксперимента.
- Архивация исходных файлов приложения — По умолчанию исходные
файлы приложения не архивируются в эксперименте. Выполните
команду gprofng archive с опцией -s all или -s used для каждого
эксперимента, чтобы сохранить исходные файлы в эксперименте.
- Автоматическая архивация исходных файлов — Переменная окружения
GPROFNG_ARCHIVE может быть установлена для автоматической
архивации исходных файлов после завершения эксперимента. Эта
переменная окружения может содержать аргументы -s и -m, как пары
аргументов и опций, разделённые одним или несколькими пробелами.
Если на командной строке появляется более одного аргумента -s,
последний имеет приоритет. Если -s передаётся на командной строке
и устанавливается переменной окружения, опция из переменной
окружения имеет приоритет.
Обратите внимание, что в случае, если автоматическая архивация
исходных файлов во время сбора данных была включена с помощью
переменной GPROFNG_ARCHIVE или опций -a src или -a usedsrc, рекомендуется
подтвердить, что исходные файлы были правильно разрешены, выполнив
команду gprofng archive -s all или gprofng archive -s used.
- Опции -d и -r являются взаимоисключающими.
- При использовании опции -d или -r переменная окружения
GPROFNG_ARCHIVE_COMMON_DIR может быть использована для указания
местоположения общего архива. Это может быть очень удобно при
использовании скрипта для профилирования приложений.
- Если на командной строке или в переменной окружения указано более
одного опции -s, указанная опция для всех должна быть одинаковой.
В противном случае gprofng archive завершается с ошибкой.
- Этот инструмент не работает с экспериментами, записанными с
помощью более ранних версий инструментов. Если он вызван для
таких экспериментов, выводится предупреждение. Используйте версию
gprofng archive из того же выпуска, с которым был записан
эксперимент.
SEE ALSO
gprofng(1), gprofng-collect-app(1), gprofng-display-html(1),
gprofng-display-src(1), gprofng-display-text(1)
Руководство пользователя для gprofng поддерживается как руководство
в формате Texinfo. Если программы info и gprofng правильно
установлены, команда info gprofng должна предоставить доступ к
этому документу.
COPYRIGHT
Copyright (c) 2022-2025 Free Software Foundation, Inc.
Разрешается копировать, распространять и/или изменять этот документ
на условиях Лицензии GNU Free Documentation License, версии 1.3 или
любой более поздней версии, опубликованной Free Software Foundation;
без Инвариантных Разделов, без Текстов на Обложке и без Текстов на
Задней Обложке. Копия лицензии включена в раздел, озаглавленный
"GNU Free Documentation License".
binutils-2.44 2025-02-02 GPROFNG-ARCHIVE(1)
GPROFNG-ARCHIVE(1) User Commands GPROFNG-ARCHIVE(1)
NAME
gprofng-archive - Archive gprofng experiment data
SYNOPSIS
gprofng archive [option(s)] experiment
DESCRIPTION
Archive the associated application binaries and source files in a
gprofng experiment to make it self contained and portable.
By default, the binaries are archived as part of the data collection,
but the application source files are not archived. Use this tool to
change this and afterwards archive additional components.
This tool has to be executed on the same system where the profiling
data was recorded.
OPTIONS
--version
Print the version number and exit.
--help
Print usage information and exit.
-a {off | on | ldobjects | src | usedldobjects | used[src]}
Specify archiving of binaries and other files. In addition to
disable this feature (off), or enable archiving of all loadobjects
and sources (on), the other choices support a more refined
selection.
All of these choices enable archiving, but the keyword controls
what exactly is selected: all load objects (ldobjects), all source
files (src), the loadobjects associated with a program counter
(usedldobjects), or the source files associated with a program
counter (used[src]). The default is -a ldobjects.
-d path
The path is the absolute path to a common archive, which is a
directory that contains archived files. If the directory does not
exist, then it will be created. Files are saved in the common
archive directory, and a symbolic link is created in the experiment
archive.
-F Force writing, or rewriting of .archive files. All archived files
will be removed and recreated, except if the -n or -m option is
used, or if the experiment is a subexperiment.
-m regex
Archive only those source, object, and debug info files whose full
path name matches the given POSIX compliant regex regular
expression.
-n Archive the named experiment only, not any of its descendants.
-q Do not write any warnings to stderr. Warnings are incorporated
into the .archive file in the experiment directory. They are shown
in the output of the gprofng display text command.
-r path
This option specifies the location of a common archive. The value
is the relative path to a common archive, which is a directory that
contains archived files. If the directory does not exist, then it
will be created. Files are saved in the common archive directory,
and a symbolic link is created in the experiment archive.
-s selection
Specify archiving of source files. The allowed values for
selection are:
no Do not archive any source files.
all Archive all source and object files that can be found.
used[src]
Archive source and object files for functions against which
data was recorded in the experiment, and that can be found.
By default, application source files are not archived into the
experiment. If the -s all, or -s used option is used, sources and
object files are archived. These options also ensure that source
files are available in the experiment, even if the original source
files have been modified, or are inaccessible afterwards.
In case archive files cannot be found, use the addpath, or pathmap
command, or both, in an .er.rc file to specify the location of the
missing file(s).
NOTES
- Archiving of application binaries - By default, binaries are
archived automatically when an experiment is created. However,
archiving does not occur in one or more of the following
circumstances:
• If the profiled application is terminated before it exits
normally.
• If a running process is profiled.
• If archiving is explicitly disabled when profiling. For
example by using the -a off option on gprofng collect app.
In these cases, gprofng archive must be run manually and on the
same machine where the profiling data was recorded.
Archiving of experiment data during the data collection process can
be quite expensive. Especially if the experiment has many
descendant processes. In such cases, a more efficient strategy is
to use the -a off option when collecting the data. Once the
collection has completed, the data can be archived using the -s all
option. This saves all executables and source files in the
experiment.
If during the archiving there is an error message that an
executable, or source file cannot be found, the addpath command to
add the path to the missing file(s) can be included in the .er.rc
file. After this command has been added, archive the experiment
again. The archiving archiving can be repeated as many times as
necessary to archive all files.
Archiving should be done on the same system as was used to collect
the experiment. If some files cannot be accessed from this system
(e.g. sources or object files), then additional archiving can be
done using another system that can access them. For example, the
system where the application was built.
Some Java applications store shared objects in jar files. By
default, such shared objects are not automatically archived. To
archive shared objects contained in jar files, make sure to include
the addpath command in an .er.rc file. The addpath command should
give the path to the jar file, including the jar file itself. The
.er.rc file should be saved in the user home directory, or
experiment parent directory.
- Archiving of application sources - By default, application source
files are not archived in the experiment. Execute the gprofng
archive command with the -s all, or -s used option on each
experiment to store source files in the experiment.
- Automatic archiving of application sources - Environment variable
GPROFNG_ARCHIVE may be set to automatically archive sources when
the experiment has completed. This environment variable can
contain -s and -m arguments, as pairs of argument and options,
separated by one or more blanks.
If more than one -s argument appears on the command line, the last
one prevails. If -s is both passed on the command line, and set by
the environment variable, the option from the environment variable
prevails.
Note that in case automatic source archiving during data collection
has been enabled using either the GPROFNG_ARCHIVE variable, or the
-a src, or -a usedsrc option, it is recommended to confirm that
source files have been correctly resolved by executing the gprofng
archive -s all, or gprofng archive -s used command.
- The -d and -r options are mutually exclusive.
- When using the -d or -r option, environment variable
GPROFNG_ARCHIVE_COMMON_DIR can be used to specify the location of
the common archive. This can be very convenient when using a
script to profile applications.
- If more than one -s option is given on the command line, or
specified in the environment variable, the specified option for all
must be the same. If not, gprofng archive exits with an error.
- This tool does not work on experiments recorded with earlier
versions of the tools. If invoked on such experiments, a warning
is printed. Use the version of gprofng archive from the same
release with which the experiment was recorded.
SEE ALSO
gprofng(1), gprofng-collect-app(1), gprofng-display-html(1),
gprofng-display-src(1), gprofng-display-text(1)
The user guide for gprofng is maintained as a Texinfo manual. If the
info and gprofng programs are correctly installed, the command info
gprofng should give access to this document.
COPYRIGHT
Copyright (c) 2022-2025 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3 or
any later version published by the Free Software Foundation; with no
Invariant Sections, with no Front-Cover Texts, and with no Back-Cover
Texts. A copy of the license is included in the section entitled "GNU
Free Documentation License".
binutils-2.44 2025-02-02 GPROFNG-ARCHIVE(1)
DLLTOOL(1) Инструменты разработки GNU DLLTOOL(1)
NAME
dlltool - создать файлы, необходимые для сборки и использования DLL
SYNOPSIS
dlltool [-d|--input-def def-файл]
[-b|--base-file base-файл]
[-e|--output-exp exports-файл]
[-z|--output-def def-файл]
[-l|--output-lib library-файл]
[-y|--output-delaylib library-файл]
[--export-all-symbols] [--no-export-all-symbols]
[--exclude-symbols список]
[--no-default-excludes]
[-S|--as путь-к-ассемблеру] [-f|--as-flags опции]
[-D|--dllname имя] [-m|--machine машина]
[-a|--add-indirect]
[-U|--add-underscore] [--add-stdcall-underscore]
[-k|--kill-at] [-A|--add-stdcall-alias]
[-p|--ext-prefix-alias префикс]
[-x|--no-idata4] [-c|--no-idata5]
[--use-nul-prefixed-import-tables]
[-I|--identify library-файл] [--identify-strict]
[-i|--interwork]
[-n|--nodelete] [-t|--temp-prefix префикс]
[-v|--verbose]
[-h|--help] [-V|--version]
[--no-leading-underscore] [--leading-underscore]
[--deterministic-libraries] [--non-deterministic-libraries]
[object-файл ...]
DESCRIPTION
dlltool читает свои входные данные, которые могут приходить из опций -d и -b, а также из object-файлов, указанных в командной строке. Затем он обрабатывает эти входные данные и, если указана опция -e, создаёт файл экспортов. Если указана опция -l, создаётся library-файл, а если указана опция -z, создаётся def-файл. Любые или все из опций -e, -l и -z могут быть указаны в одном вызове dlltool.
При создании DLL, наряду с исходным кодом DLL, необходимо иметь три других файла. dlltool может помочь в создании этих файлов.
Первый файл — это .def-файл, который указывает, какие функции экспортируются из DLL, какие функции импортирует DLL и так далее. Это текстовый файл, и его можно создать вручную, или dlltool может создать его с помощью опции -z. В этом случае dlltool сканирует object-файлы, указанные в командной строке, в поисках функций, специально помеченных как экспортируемые, и добавляет записи для них в .def-файл.
Чтобы пометить функцию как экспортируемую из DLL, в ней должна быть запись -export:<имя_функции> в секции .drectve object-файла. Это можно сделать в C с помощью оператора asm():
asm (".section .drectve");
asm (".ascii "-export:my_func"");
int my_func (void) { ... }
Второй файл, необходимый для создания DLL, — это файл экспортов. Этот файл связывается с object-файлами, составляющими тело DLL, и обрабатывает интерфейс между DLL и внешним миром. Это двоичный файл, и его можно создать, указав опцию -e для dlltool при создании или чтении .def-файла.
Третий файл, необходимый для создания DLL, — это library-файл, с которым программы будут связываться для доступа к функциям в DLL (библиотека импорта). Этот файл можно создать, указав опцию -l для dlltool при создании или чтении .def-файла.
Если указана опция -y, dlltool генерирует delay-import library, которую можно использовать вместо обычной библиотеки импорта, чтобы программа связывалась с DLL только при первом вызове импортированной функции. Получившийся исполняемый файл должен быть связан со статической библиотекой delayimp, содержащей __delayLoadHelper2(), которая, в свою очередь, импортирует LoadLibraryA и GetProcAddress из kernel32.
dlltool создаёт library-файл вручную, но для создания файла экспортов он создаёт временные файлы с инструкциями ассемблера, а затем собирает их. Опция командной строки -S может использоваться для указания пути к ассемблеру, который будет использоваться dlltool, а опция -f — для передачи конкретных флагов этому ассемблеру. Опция -n может использоваться, чтобы предотвратить удаление dlltool временных файлов ассемблера после завершения, а если -n указана дважды, это предотвратит удаление временных object-файлов, используемых для создания library-файла.
Вот пример создания DLL из исходного файла dll.c и создания программы (из object-файла program.o), которая использует эту DLL:
gcc -c dll.c
dlltool -e exports.o -l dll.lib dll.o
gcc dll.o exports.o -o dll.dll
gcc program.o dll.lib -o program
dlltool также может использоваться для запроса существующей библиотеки импорта, чтобы определить имя связанной с ней DLL. См. описание опции -I или --identify.
OPTIONS
Опции командной строки имеют следующее значение:
-d имя_файла
--input-def имя_файла
Указывает имя .def-файла, который будет прочитан и обработан.
-b имя_файла
--base-file имя_файла
Указывает имя base-файла, который будет прочитан и обработан. Содержимое этого файла будет добавлено в секцию релокаций в файле экспортов, созданном dlltool.
-e имя_файла
--output-exp имя_файла
Указывает имя файла экспортов, который будет создан dlltool.
-z имя_файла
--output-def имя_файла
Указывает имя .def-файла, который будет создан dlltool.
-l имя_файла
--output-lib имя_файла
Указывает имя library-файла, который будет создан dlltool.
-y имя_файла
--output-delaylib имя_файла
Указывает имя файла delay-import library, который будет создан dlltool.
--deterministic-libraries
--non-deterministic-libraries
При создании выходных библиотек в ответ на опции --output-lib или --output-delaylib использовать значение нуля для любых временных меток, идентификаторов пользователей и групп (--deterministic-libraries) или фактические временные метки, идентификаторы пользователей и групп (--non-deterministic-libraries).
--export-all-symbols
Рассматривать все глобальные и слабые определённые символы, найденные во входных object-файлах, как символы для экспорта. Есть небольшой список символов, которые не экспортируются по умолчанию; см. опцию --no-default-excludes. Вы можете добавить символы в список для неэкспорта с помощью опции --exclude-symbols.
--no-export-all-symbols
Экспортировать только символы, явно указанные в входном .def-файле или в секциях .drectve во входных object-файлах. Это поведение по умолчанию. Секции .drectve создаются атрибутами dllexport в исходном коде.
--exclude-symbols список
Не экспортировать символы из списка. Это список имён символов, разделённых запятыми или двоеточиями. Имена символов не должны содержать начального подчёркивания. Это имеет смысл только при использовании --export-all-symbols.
--no-default-excludes
Когда используется --export-all-symbols, по умолчанию оно избегает экспорта определённых специальных символов. Текущий список символов для избежания экспорта: DllMain@12, DllEntryPoint@0, impure_ptr. Вы можете использовать опцию --no-default-excludes, чтобы всё равно экспортировать эти специальные символы. Это имеет смысл только при использовании --export-all-symbols.
-S путь
--as путь
Указывает путь, включая имя файла, ассемблера, который будет использоваться для создания файла экспортов.
-f опции
--as-flags опции
Указывает любые конкретные опции командной строки, которые будут переданы ассемблеру при сборке файла экспортов. Эта опция работает даже если не используется -S. Эта опция принимает только один аргумент, и если она встречается более одного раза в командной строке, более поздние вхождения перезапишут предыдущие. Таким образом, если необходимо передать несколько опций ассемблеру, их следует заключить в двойные кавычки.
-D имя
--dll-name имя
Указывает имя, которое будет сохранено в .def-файле как имя DLL при использовании опции -e. Если эта опция отсутствует, то имя файла, указанное в опции -e, будет использовано как имя DLL.
-m машина
--machine машина
Указывает тип машины, для которой должна быть собрана library. dlltool имеет встроенный тип по умолчанию, в зависимости от того, как он был создан, но эта опция может переопределить его. Это обычно полезно только при создании DLL для процессора ARM, когда содержимое DLL фактически закодировано с использованием инструкций Thumb.
-a
--add-indirect
Указывает, что при создании файла экспортов dlltool должен добавить секцию, которая позволяет ссылаться на экспортируемые функции без использования библиотеки импорта. Что бы это ни значило!
-U
--add-underscore
Указывает, что при создании файла экспортов dlltool должен добавлять подчёркивание в начало имён всех экспортируемых символов.
--no-leading-underscore
--leading-underscore
Указывает, должны ли стандартные символы принудительно предваряться подчёркиванием или нет.
--add-stdcall-underscore
Указывает, что при создании файла экспортов dlltool должен добавлять подчёркивание в начало имён экспортируемых stdcall-функций. Имена переменных и не-stdcall-функций не изменяются. Эта опция полезна при создании импортных библиотек, совместимых с GNU, для сторонних DLL, которые были собраны с использованием инструментов MS-Windows.
-k
--kill-at
Указывает, что суффиксы @<число> должны быть omitted из имён stdcall-функций, которые будут импортированы из DLL. Это полезно при создании библиотеки импорта для DLL, которая экспортирует stdcall-функции, но без обычного суффикса @<число> в имени символа.
Это не изменяет именование символов, предоставляемых библиотекой импорта программам, связанным с ней, а только записи в таблице импорта (т.е. секция .idata).
-A
--add-stdcall-alias
Указывает, что при создании файла экспортов dlltool должен добавлять псевдонимы для stdcall-символов без @<число> в дополнение к символам с @<число>.
-p
--ext-prefix-alias префикс
Заставляет dlltool создавать внешние псевдонимы для всех импортов DLL с указанным префиксом. Псевдонимы создаются для как внешних, так и импортных символов без начального подчёркивания.
-x
--no-idata4
Указывает, что при создании файлов экспортов и library dlltool должен пропускать секцию ".idata4". Это для совместимости с определёнными операционными системами.
--use-nul-prefixed-import-tables
Указывает, что при создании файлов экспортов и library dlltool должен предварять ".idata4" и ".idata5" нулевым элементом. Это эмулирует старый способ генерации импортных библиотек "dlltool" от GNU. По умолчанию эта опция отключена.
-c
--no-idata5
Указывает, что при создании файлов экспортов и library dlltool должен пропускать секцию ".idata5". Это для совместимости с определёнными операционными системами.
-I имя_файла
--identify имя_файла
Указывает, что dlltool должен проверить библиотеку импорта, указанную в имени_файла, и вывести на "stdout" имя(я) связанной(ых) DLL(ы). Это может выполняться в дополнение к любым другим операциям, указанным другими опциями и аргументами. dlltool завершается с ошибкой, если библиотека импорта не существует или не является библиотекой импорта. См. также --identify-strict.
--identify-strict
Изменяет поведение опции --identify так, что выводится ошибка, если имя_файла связано более чем с одной DLL.
-i
--interwork
Указывает, что dlltool должен помечать object в library-файле и файле экспортов, которые он производит, как поддерживающие взаимодействие между кодом ARM и Thumb.
-n
--nodelete
Заставляет dlltool сохранять временные файлы ассемблера, которые он использовал для создания файла экспортов. Если эта опция указана повторно, dlltool также сохранит временные object-файлы, которые он использует для создания library-файла.
-t префикс
--temp-prefix префикс
Заставляет dlltool использовать префикс при формировании имён временных файлов ассемблера и object. По умолчанию префикс временного файла генерируется из PID.
-v
--verbose
Заставляет dlltool описывать, что он делает.
-h
--help
Выводит список опций командной строки и выходит.
-V
--version
Выводит номер версии dlltool и выходит.
@file
Читает опции командной строки из file. Прочитанные опции вставляются на место оригинальной опции @file. Если file не существует или не может быть прочитан, опция будет обработана буквально, без удаления.
Опции в file разделяются пробелами. Пробельный символ может быть включён в опцию, если вся опция заключена в одинарные или двойные кавычки. Любые символы (включая обратный слеш) могут быть включены путём добавления перед ними обратного слеша. Файл может сам содержать дополнительные опции @file; такие опции будут обработаны рекурсивно.
SEE ALSO
Страницы Info для binutils.
COPYRIGHT
Copyright (c) 1991-2025 Free Software Foundation, Inc.
Разрешается копировать, распространять и/или модифицировать этот документ в соответствии с условиями Лицензии GNU Free Documentation License, версии 1.3 или любой более поздней версии, опубликованной Free Software Foundation; без Неизменяемых Разделов, без Текстов Обложки и без Текстов Задней Обложки. Копия лицензии включена в раздел, озаглавленный "GNU Free Documentation License".
binutils-2.44 2025-05-12 DLLTOOL(1)
DLLTOOL(1) GNU Development Tools DLLTOOL(1)
NAME
dlltool - create files needed to build and use DLLs
SYNOPSIS
dlltool [-d|--input-def def-file-name]
[-b|--base-file base-file-name]
[-e|--output-exp exports-file-name]
[-z|--output-def def-file-name]
[-l|--output-lib library-file-name]
[-y|--output-delaylib library-file-name]
[--export-all-symbols] [--no-export-all-symbols]
[--exclude-symbols list]
[--no-default-excludes]
[-S|--as path-to-assembler] [-f|--as-flags options]
[-D|--dllname name] [-m|--machine machine]
[-a|--add-indirect]
[-U|--add-underscore] [--add-stdcall-underscore]
[-k|--kill-at] [-A|--add-stdcall-alias]
[-p|--ext-prefix-alias prefix]
[-x|--no-idata4] [-c|--no-idata5]
[--use-nul-prefixed-import-tables]
[-I|--identify library-file-name] [--identify-strict]
[-i|--interwork]
[-n|--nodelete] [-t|--temp-prefix prefix]
[-v|--verbose]
[-h|--help] [-V|--version]
[--no-leading-underscore] [--leading-underscore]
[--deterministic-libraries] [--non-deterministic-libraries]
[object-file ...]
DESCRIPTION
dlltool reads its inputs, which can come from the -d and -b options as
well as object files specified on the command line. It then processes
these inputs and if the -e option has been specified it creates a
exports file. If the -l option has been specified it creates a library
file and if the -z option has been specified it creates a def file.
Any or all of the -e, -l and -z options can be present in one
invocation of dlltool.
When creating a DLL, along with the source for the DLL, it is necessary
to have three other files. dlltool can help with the creation of these
files.
The first file is a .def file which specifies which functions are
exported from the DLL, which functions the DLL imports, and so on.
This is a text file and can be created by hand, or dlltool can be used
to create it using the -z option. In this case dlltool will scan the
object files specified on its command line looking for those functions
which have been specially marked as being exported and put entries for
them in the .def file it creates.
In order to mark a function as being exported from a DLL, it needs to
have an -export:<name_of_function> entry in the .drectve section of the
object file. This can be done in C by using the asm() operator:
asm (".section .drectve");
asm (".ascii \"-export:my_func\"");
int my_func (void) { ... }
The second file needed for DLL creation is an exports file. This file
is linked with the object files that make up the body of the DLL and it
handles the interface between the DLL and the outside world. This is a
binary file and it can be created by giving the -e option to dlltool
when it is creating or reading in a .def file.
The third file needed for DLL creation is the library file that
programs will link with in order to access the functions in the DLL (an
`import library'). This file can be created by giving the -l option to
dlltool when it is creating or reading in a .def file.
If the -y option is specified, dlltool generates a delay-import library
that can be used instead of the normal import library to allow a
program to link to the dll only as soon as an imported function is
called for the first time. The resulting executable will need to be
linked to the static delayimp library containing __delayLoadHelper2(),
which in turn will import LoadLibraryA and GetProcAddress from
kernel32.
dlltool builds the library file by hand, but it builds the exports file
by creating temporary files containing assembler statements and then
assembling these. The -S command-line option can be used to specify
the path to the assembler that dlltool will use, and the -f option can
be used to pass specific flags to that assembler. The -n can be used
to prevent dlltool from deleting these temporary assembler files when
it is done, and if -n is specified twice then this will prevent dlltool
from deleting the temporary object files it used to build the library.
Here is an example of creating a DLL from a source file dll.c and also
creating a program (from an object file called program.o) that uses
that DLL:
gcc -c dll.c
dlltool -e exports.o -l dll.lib dll.o
gcc dll.o exports.o -o dll.dll
gcc program.o dll.lib -o program
dlltool may also be used to query an existing import library to
determine the name of the DLL to which it is associated. See the
description of the -I or --identify option.
OPTIONS
The command-line options have the following meanings:
-d filename
--input-def filename
Specifies the name of a .def file to be read in and processed.
-b filename
--base-file filename
Specifies the name of a base file to be read in and processed. The
contents of this file will be added to the relocation section in
the exports file generated by dlltool.
-e filename
--output-exp filename
Specifies the name of the export file to be created by dlltool.
-z filename
--output-def filename
Specifies the name of the .def file to be created by dlltool.
-l filename
--output-lib filename
Specifies the name of the library file to be created by dlltool.
-y filename
--output-delaylib filename
Specifies the name of the delay-import library file to be created
by dlltool.
--deterministic-libraries
--non-deterministic-libraries
When creating output libraries in response to either the
--output-lib or --output-delaylib options either use the value of
zero for any timestamps, user ids and group ids created
(--deterministic-libraries) or the actual timestamps, user ids and
group ids (--non-deterministic-libraries).
--export-all-symbols
Treat all global and weak defined symbols found in the input object
files as symbols to be exported. There is a small list of symbols
which are not exported by default; see the --no-default-excludes
option. You may add to the list of symbols to not export by using
the --exclude-symbols option.
--no-export-all-symbols
Only export symbols explicitly listed in an input .def file or in
.drectve sections in the input object files. This is the default
behaviour. The .drectve sections are created by dllexport
attributes in the source code.
--exclude-symbols list
Do not export the symbols in list. This is a list of symbol names
separated by comma or colon characters. The symbol names should
not contain a leading underscore. This is only meaningful when
--export-all-symbols is used.
--no-default-excludes
When --export-all-symbols is used, it will by default avoid
exporting certain special symbols. The current list of symbols to
avoid exporting is DllMain@12, DllEntryPoint@0, impure_ptr. You
may use the --no-default-excludes option to go ahead and export
these special symbols. This is only meaningful when
--export-all-symbols is used.
-S path
--as path
Specifies the path, including the filename, of the assembler to be
used to create the exports file.
-f options
--as-flags options
Specifies any specific command-line options to be passed to the
assembler when building the exports file. This option will work
even if the -S option is not used. This option only takes one
argument, and if it occurs more than once on the command line, then
later occurrences will override earlier occurrences. So if it is
necessary to pass multiple options to the assembler they should be
enclosed in double quotes.
-D name
--dll-name name
Specifies the name to be stored in the .def file as the name of the
DLL when the -e option is used. If this option is not present,
then the filename given to the -e option will be used as the name
of the DLL.
-m machine
-machine machine
Specifies the type of machine for which the library file should be
built. dlltool has a built in default type, depending upon how it
was created, but this option can be used to override that. This is
normally only useful when creating DLLs for an ARM processor, when
the contents of the DLL are actually encode using Thumb
instructions.
-a
--add-indirect
Specifies that when dlltool is creating the exports file it should
add a section which allows the exported functions to be referenced
without using the import library. Whatever the hell that means!
-U
--add-underscore
Specifies that when dlltool is creating the exports file it should
prepend an underscore to the names of all exported symbols.
--no-leading-underscore
--leading-underscore
Specifies whether standard symbol should be forced to be prefixed,
or not.
--add-stdcall-underscore
Specifies that when dlltool is creating the exports file it should
prepend an underscore to the names of exported stdcall functions.
Variable names and non-stdcall function names are not modified.
This option is useful when creating GNU-compatible import libs for
third party DLLs that were built with MS-Windows tools.
-k
--kill-at
Specifies that @<number> suffixes should be omitted from the names
of stdcall functions that will be imported from the DLL. This is
useful when creating an import library for a DLL which exports
stdcall functions but without the usual @<number> symbol name
suffix.
This does not change the naming of symbols provided by the import
library to programs linked against it, but only the entries in the
import table (ie the .idata section).
-A
--add-stdcall-alias
Specifies that when dlltool is creating the exports file it should
add aliases for stdcall symbols without @ <number> in addition to
the symbols with @ <number>.
-p
--ext-prefix-alias prefix
Causes dlltool to create external aliases for all DLL imports with
the specified prefix. The aliases are created for both external
and import symbols with no leading underscore.
-x
--no-idata4
Specifies that when dlltool is creating the exports and library
files it should omit the ".idata4" section. This is for
compatibility with certain operating systems.
--use-nul-prefixed-import-tables
Specifies that when dlltool is creating the exports and library
files it should prefix the ".idata4" and ".idata5" by zero an
element. This emulates old gnu import library generation of
"dlltool". By default this option is turned off.
-c
--no-idata5
Specifies that when dlltool is creating the exports and library
files it should omit the ".idata5" section. This is for
compatibility with certain operating systems.
-I filename
--identify filename
Specifies that dlltool should inspect the import library indicated
by filename and report, on "stdout", the name(s) of the associated
DLL(s). This can be performed in addition to any other operations
indicated by the other options and arguments. dlltool fails if the
import library does not exist or is not actually an import library.
See also --identify-strict.
--identify-strict
Modifies the behavior of the --identify option, such that an error
is reported if filename is associated with more than one DLL.
-i
--interwork
Specifies that dlltool should mark the objects in the library file
and exports file that it produces as supporting interworking
between ARM and Thumb code.
-n
--nodelete
Makes dlltool preserve the temporary assembler files it used to
create the exports file. If this option is repeated then dlltool
will also preserve the temporary object files it uses to create the
library file.
-t prefix
--temp-prefix prefix
Makes dlltool use prefix when constructing the names of temporary
assembler and object files. By default, the temp file prefix is
generated from the pid.
-v
--verbose
Make dlltool describe what it is doing.
-h
--help
Displays a list of command-line options and then exits.
-V
--version
Displays dlltool's version number and then exits.
@file
Read command-line options from file. The options read are inserted
in place of the original @file option. If file does not exist, or
cannot be read, then the option will be treated literally, and not
removed.
Options in file are separated by whitespace. A whitespace
character may be included in an option by surrounding the entire
option in either single or double quotes. Any character (including
a backslash) may be included by prefixing the character to be
included with a backslash. The file may itself contain additional
@file options; any such options will be processed recursively.
SEE ALSO
The Info pages for binutils.
COPYRIGHT
Copyright (c) 1991-2025 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3 or
any later version published by the Free Software Foundation; with no
Invariant Sections, with no Front-Cover Texts, and with no Back-Cover
Texts. A copy of the license is included in the section entitled "GNU
Free Documentation License".
binutils-2.44 2025-05-12 DLLTOOL(1)
GPROFNG(1) User Commands GPROFNG(1)
NAME
gprofng - Инструмент профилирования приложений следующего поколения GNU
SYNOPSIS
gprofng [option(s)] action [qualifier] [option(s)] target [options]
DESCRIPTION
Это драйвер для набора инструментов gprofng для сбора и анализа данных производительности.
Драйвер выполняет указанное действие. Примером действия является collect для сбора данных производительности. В зависимости от действия, может потребоваться квалификатор для дальнейшего определения команды. Последним элементом является цель, к которой применяется команда.
Есть три места, где поддерживаются опции. Драйвер поддерживает опции. Их можно найти ниже. Действие, возможно, в сочетании с квалификатором, также поддерживает опции. Описание этих опций можно найти в man-странице для команды. Любые опции, необходимые для выполнения команды цели, должны следовать за именем цели.
Например, для сбора данных производительности для приложения под названием a.out и хранения результатов в каталоге эксперимента mydata.er, может быть использована следующая команда:
$ gprofng collect app -o mydata.er a.out -t 2
В этом примере, действие - collect, квалификатор - app, единственный аргумент команды - "-o mydata.er", а цель - a.out. Команда цели вызывается с опцией -t 2.
Если gprofng выполняется без каких-либо дополнительных опций, действий или цели, выводится обзор использования.
OPTIONS
--version
Вывести номер версии и выйти.
--help
Вывести информацию об использовании и выйти.
ENVIRONMENT
Поддерживаются следующие переменные окружения:
GPROFNG_MAX_CALL_STACK_DEPTH
Установить глубину стека вызовов (по умолчанию 256).
GPROFNG_USE_JAVA_OPTIONS
Может быть установлено при профилировании приложения C/C++, которое использует dlopen() для выполнения кода Java.
GPROFNG_ALLOW_CORE_DUMP
Установить эту переменную, чтобы разрешить генерацию файла core; в противном случае создаётся отчёт об ошибке в /tmp.
GPROFNG_ARCHIVE
Использовать эту переменную для определения настроек автоматического архивирования при завершении записи эксперимента.
GPROFNG_ARCHIVE_COMMON_DIR
Установить эту переменную на расположение общего архива.
GPROFNG_JAVA_MAX_CALL_STACK_DEPTH
Установить глубину стека вызовов Java; по умолчанию 256; установить в 0, чтобы отключить захват стеков вызовов.
GPROFNG_JAVA_NATIVE_MAX_CALL_STACK_DEPTH
Установить глубину стека вызовов нативных Java; по умолчанию 256; установить в 0, чтобы отключить захват стеков вызовов (стековые вызовы JNI и ассемблера не захватываются).
GPROFNG_SYSCONFDIR
Установить путь к файлу конфигурации gprofng.rc. По умолчанию этот файл размещается в подкаталоге etc директории установки binutils. В случае использования RPM для установки, этот файл находится в директории /etc.
При сборке и установке из исходников пользователь может установить путь к этому файлу конфигурации в нестандартное место. Если это так, пользователь может установить переменную окружения "GPROFNG_SYSCONFDIR", чтобы указать на это место.
В противном случае, инструменты gprofng display text, gprofng display src и gprofng archive не смогут найти этот файл.
NOTES
Драйвер gprofng поддерживает следующие команды.
Сбор данных производительности:
"gprofng collect app"
Собрать данные производительности приложения.
Отображение результатов производительности:
"gprofng display text"
Отобразить данные производительности в формате ASCII.
"gprofng display html"
Сгенерировать HTML-файл из одного или нескольких экспериментов.
"gprofng display gui"
Запустить графический интерфейс. Обратите внимание, что этот инструмент не доступен по умолчанию и нуждается в отдельной установке.
Разные команды:
"gprofng display src"
Отобразить исходный код или дизассемблированный код с аннотациями компилятора.
"gprofng archive"
Включить бинарники и исходный код в каталог эксперимента.
Также возможно вызвать низкоуровневые команды напрямую, но поскольку эти команды могут измениться, в частности опции, мы рекомендуем использовать драйвер.
Графический интерфейс gprofng - это необязательный инструмент, который предоставляет графический интерфейс для "gprofng". Он простой в использовании и поддерживает множество видов данных производительности. Для тех, кто интересуется этим GUI, мы рекомендуем поискать "gprofng-gui", как получить, установить и использовать его.
SEE ALSO
gprofng-archive(1), gprofng-collect-app(1), gprofng-display-html(1),
gprofng-display-src(1), gprofng-display-text(1)
Каждая команда gprofng также поддерживает опцию --help. Это перечисляет опции и краткое описание для каждой опции.
Например, это отобразит опции, поддерживаемые командой gprofng collect app:
$ gprofng collect app --help
Руководство пользователя для gprofng поддерживается как руководство Texinfo. Если программы info и gprofng правильно установлены, команда info gprofng должна предоставить доступ к этому документу.
COPYRIGHT
Copyright (c) 2022-2025 Free Software Foundation, Inc.
Разрешается копировать, распространять и/или модифицировать этот документ на условиях Лицензии GNU Free Documentation License, версии 1.3 или любой более поздней версии, опубликованной Free Software Foundation; без Инвариантных Разделов, без Текстов на Обложке и без Текстов на Задней Обложке. Копия лицензии включена в раздел, озаглавленный "GNU Free Documentation License".
binutils-2.44 2025-02-02 GPROFNG(1)
GPROFNG(1) User Commands GPROFNG(1)
NAME
gprofng - The next generation GNU application profiling tool
SYNOPSIS
gprofng [option(s)] action [qualifier] [option(s)] target [options]
DESCRIPTION
This is the driver for the gprofng tools suite to gather and analyze
performance data.
The driver executes the action specified. An example of an action is
collect to collect performance data. Depending on the action, a
qualifier may be needed to further define the command. The last item
is the target that the command applies to.
There are three places where options are supported. The driver
supports options. These can be found below. The action, possibly in
combination with the qualifier also supports options. A description of
these can be found in the man page for the command. Any options needed
to execute the target command should follow the target name.
For example, to collect performance data for an application called
a.out and store the results in experiment directory mydata.er, the
following command may be used:
$ gprofng collect app -o mydata.er a.out -t 2
In this example, the action is collect, the qualifier is app, the
single argument to the command is "-o mydata.er" and the target is
a.out. The target command is invoked with the -t 2 option.
If gprofng is executed without any additional option, action, or
target, a usage overview is printed.
OPTIONS
--version
Print the version number and exit.
--help
Print usage information and exit.
ENVIRONMENT
The following environment variables are supported:
GPROFNG_MAX_CALL_STACK_DEPTH
Set the depth of the call stack (default is 256).
GPROFNG_USE_JAVA_OPTIONS
May be set when profiling a C/C++ application that uses dlopen() to
execute Java code.
GPROFNG_ALLOW_CORE_DUMP
Set this variable to allow a core file to be generated; otherwise
an error report is created on /tmp.
GPROFNG_ARCHIVE
Use this variable to define the settings for automatic archiving
upon experiment recording completion.
GPROFNG_ARCHIVE_COMMON_DIR
Set this variable to the location of the common archive.
GPROFNG_JAVA_MAX_CALL_STACK_DEPTH
Set the depth of the Java call stack; the default is 256; set to 0
to disable capturing of call stacks.
GPROFNG_JAVA_NATIVE_MAX_CALL_STACK_DEPTH
Set the depth of the Java native call stack; the default is 256;
set to 0 to disable capturing of call stacks (JNI and assembly call
stacks are not captured).
GPROFNG_SYSCONFDIR
Set the path to the gprofng.rc configuration file. By default,
this file is placed in the etc subdirectory of the binutils
installation directory. In case an RPM has been used for the
installation, this file is in directory /etc.
When building and installing from the source, the user can set the
path to this configuration file to a non-default location. If this
is the case, the user may set the "GPROFNG_SYSCONFDIR" environment
variable to point to this location.
Otherwise, the gprofng display text, gprofng display src, and
gprofng archive tools cannot find this file.
NOTES
The gprofng driver supports the following commands.
Collect performance data:
"gprofng collect app"
Collect application performance data.
Display the performance results:
"gprofng display text"
Display the performance data in ASCII format.
"gprofng display html"
Generate an HTML file from one or more experiments.
"gprofng display gui"
Start the GUI. Note that this tool is not available by default and
needs to be installed seperately.
Miscellaneous commands:
"gprofng display src"
Display source or disassembly with compiler annotations.
"gprofng archive"
Include binaries and source code in an experiment directory.
It is also possible to invoke the lower level commands directly, but
since these are subject to change, in particular the options, we
recommend to use the driver.
The gprofng GUI is an optional tool that provides a graphical interface
for "gprofng". It is easy to use and supports many views into the
performance data. For those interested in this GUI, we recommend to
search for "gprofng-gui" how to obtain, install and use it.
SEE ALSO
gprofng-archive(1), gprofng-collect-app(1), gprofng-display-html(1),
gprofng-display-src(1), gprofng-display-text(1)
Each gprofng command also supports the --help option. This lists the
options and a short description for each option.
For example this displays the options supported on the gprofng collect
app command:
$ gprofng collect app --help
The user guide for gprofng is maintained as a Texinfo manual. If the
info and gprofng programs are correctly installed, the command info
gprofng should give access to this document.
COPYRIGHT
Copyright (c) 2022-2025 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3 or
any later version published by the Free Software Foundation; with no
Invariant Sections, with no Front-Cover Texts, and with no Back-Cover
Texts. A copy of the license is included in the section entitled "GNU
Free Documentation License".
binutils-2.44 2025-02-02 GPROFNG(1)
ADDR2LINE(1) GNU Development Tools ADDR2LINE(1)
NAME
addr2line - преобразует адреса или symbol+offset в имена файлов и номера строк
SYNOPSIS
addr2line [-a|--addresses]
[-b bfdname|--target=bfdname]
[-C|--demangle[=style]]
[-r|--no-recurse-limit]
[-R|--recurse-limit]
[-e filename|--exe=filename]
[-f|--functions] [-s|--basename]
[-i|--inlines]
[-p|--pretty-print]
[-j|--section=name]
[-H|--help] [-V|--version]
[addr addr ...]
DESCRIPTION
addr2line преобразует адреса или symbol+offset в имена файлов и номера строк. При указании адреса или symbol+offset в исполняемом файле или смещения в разделе переставляемого объекта, он использует отладочную информацию, чтобы определить, какой файл и номер строки с ним ассоциированы.
Исполняемый файл или переставляемый объект, который будет использоваться, указывается с опцией -e. По умолчанию используется файл a.out. Раздел в переставляемом объекте, который будет использоваться, указывается с опцией -j.
addr2line имеет два режима работы.
В первом режиме на командной строке указываются шестнадцатеричные адреса или symbol+offset, и addr2line отображает имя файла и номер строки для каждого адреса.
Во втором режиме addr2line читает шестнадцатеричные адреса или symbol+offset из стандартного ввода и выводит имя файла и номер строки для каждого адреса в стандартный вывод. В этом режиме addr2line может использоваться в конвейере для преобразования динамически выбранных адресов.
Формат вывода — FILENAME:LINENO. По умолчанию каждый входной адрес генерирует одну строку вывода.
Две опции могут генерировать дополнительные строки перед строкой FILENAME:LINENO (в указанном порядке).
Если используется опция -a, то отображается строка с входным адресом.
Если используется опция -f, то отображается строка с именем функции FUNCTIONNAME. Это имя функции, содержащей адрес.
Одна опция может генерировать дополнительные строки после строки FILENAME:LINENO.
Если используется опция -i и код по данному адресу присутствует из-за встроенного компилятором кода, то после этого отображаются дополнительные строки. Для каждой встроенной функции отображаются одна или две дополнительные строки (если используется опция -f).
Альтернативно, если используется опция -p, то каждый входной адрес генерирует одну длинную строку вывода, содержащую адрес, имя функции, имя файла и номер строки. Если также использована опция -i, то любые встроенные функции будут отображаться аналогично, но на отдельных строках и с префиксом (inlined by).
Если имя файла или имя функции определить невозможно, addr2line выведет два знака вопроса на их месте. Если номер строки определить невозможно, addr2line выведет 0.
При использовании symbol+offset, +offset является необязательным, за исключением случаев, когда символ неоднозначен с шестнадцатеричным числом. Разрешенные символы могут быть искаженными или неискаженными, за исключением неискаженных символов с +.
OPTIONS
Длинные и короткие формы опций, показанные здесь как альтернативы, эквивалентны.
-a
--addresses
Отображать адрес перед информацией о имени функции, файле и номере строки. Адрес выводится с префиксом 0x для легкой идентификации.
-b bfdname
--target=bfdname
Указывать формат объектного кода для объектных файлов как bfdname.
-C
--demangle[=style]
Декодировать (разискать) низкоуровневые имена символов в пользовательские имена. Кроме удаления начального подчеркивания, добавленного системой, это делает читаемыми имена функций C++. Разные компиляторы имеют разные стили искажения. Необязательный аргумент стиля разыска может быть использован для выбора подходящего стиля разыска для вашего компилятора.
-e filename
--exe=filename
Указывать имя исполняемого файла, для которого должны быть преобразованы адреса. Файл по умолчанию — a.out.
-f
--functions
Отображать имена функций, а также информацию о файле и номере строки.
-s
--basenames
Отображать только базовое имя каждого файла.
-i
--inlines
Если адрес принадлежит функции, которая была встроена, то информация об источнике для всех охватывающих областей до первой не встроенной функции также будет выведена. Например, если "main" встроила "callee1", которая встроила "callee2", и адрес из "callee2", то информация об источнике для "callee1" и "main" также будет выведена.
-j
--section
Читать смещения относительно указанного раздела, а не абсолютных адресов.
-p
--pretty-print
Делать вывод более удобным для человека: каждое местоположение выводится на одной строке. Если указана опция -i, строки для всех охватывающих областей будут начинаться с префикса (inlined by).
-r
-R
--recurse-limit
--no-recurse-limit
--recursion-limit
--no-recursion-limit
Включать или отключать ограничение на количество рекурсии при разыскании строк. Поскольку форматы искажения имен позволяют бесконечный уровень рекурсии, возможно создание строк, декодирование которых израсходует объем доступного стека на хост-машине, вызывая ошибку памяти. Ограничение пытается предотвратить это, ограничивая рекурсию 2048 уровнями вложенности.
По умолчанию это ограничение включено, но отключение может быть необходимым для разыскания действительно сложных имен. Однако, если ограничение рекурсии отключено, возможен переполнение стека, и любые отчеты об ошибках такого события будут отклонены.
Опция -r является синонимом для --no-recurse-limit. Опция -R является синонимом для --recurse-limit.
Обратите внимание, что эта опция действует только если включена опция -C или --demangle.
@file
Читать параметры командной строки из файла. Прочитанные параметры вставляются на место оригинальной опции @file. Если файл не существует или не может быть прочитан, опция будет обработана буквально, без удаления.
Параметры в файле разделяются пробелами. Пробельный символ может быть включен в параметр, если весь параметр заключен в одинарные или двойные кавычки. Любые символы (включая обратную косую черту) могут быть включены путем добавления перед ними обратной косой черты. Файл может сам содержать дополнительные опции @file; такие опции будут обработаны рекурсивно.
SEE ALSO
Info entries for binutils.
COPYRIGHT
Copyright (c) 1991-2025 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3 or
any later version published by the Free Software Foundation; with no
Invariant Sections, with no Front-Cover Texts, and with no Back-Cover
Texts. A copy of the license is included in the section entitled "GNU
Free Documentation License".
binutils-2.44 2025-05-12 ADDR2LINE(1)
ADDR2LINE(1) GNU Development Tools ADDR2LINE(1)
NAME
addr2line - convert addresses or symbol+offset into file names and line
numbers
SYNOPSIS
addr2line [-a|--addresses]
[-b bfdname|--target=bfdname]
[-C|--demangle[=style]]
[-r|--no-recurse-limit]
[-R|--recurse-limit]
[-e filename|--exe=filename]
[-f|--functions] [-s|--basename]
[-i|--inlines]
[-p|--pretty-print]
[-j|--section=name]
[-H|--help] [-V|--version]
[addr addr ...]
DESCRIPTION
addr2line translates addresses or symbol+offset into file names and
line numbers. Given an address or symbol+offset in an executable or an
offset in a section of a relocatable object, it uses the debugging
information to figure out which file name and line number are
associated with it.
The executable or relocatable object to use is specified with the -e
option. The default is the file a.out. The section in the relocatable
object to use is specified with the -j option.
addr2line has two modes of operation.
In the first, hexadecimal addresses or symbol+offset are specified on
the command line, and addr2line displays the file name and line number
for each address.
In the second, addr2line reads hexadecimal addresses or symbol+offset
from standard input, and prints the file name and line number for each
address on standard output. In this mode, addr2line may be used in a
pipe to convert dynamically chosen addresses.
The format of the output is FILENAME:LINENO. By default each input
address generates one line of output.
Two options can generate additional lines before each FILENAME:LINENO
line (in that order).
If the -a option is used then a line with the input address is
displayed.
If the -f option is used, then a line with the FUNCTIONNAME is
displayed. This is the name of the function containing the address.
One option can generate additional lines after the FILENAME:LINENO
line.
If the -i option is used and the code at the given address is present
there because of inlining by the compiler then additional lines are
displayed afterwards. One or two extra lines (if the -f option is
used) are displayed for each inlined function.
Alternatively if the -p option is used then each input address
generates a single, long, output line containing the address, the
function name, the file name and the line number. If the -i option has
also been used then any inlined functions will be displayed in the same
manner, but on separate lines, and prefixed by the text (inlined by).
If the file name or function name can not be determined, addr2line will
print two question marks in their place. If the line number can not be
determined, addr2line will print 0.
When symbol+offset is used, +offset is optional, except when the symbol
is ambigious with a hex number. The resolved symbols can be mangled or
unmangled, except unmangled symbols with + are not allowed.
OPTIONS
The long and short forms of options, shown here as alternatives, are
equivalent.
-a
--addresses
Display the address before the function name, file and line number
information. The address is printed with a 0x prefix to easily
identify it.
-b bfdname
--target=bfdname
Specify that the object-code format for the object files is
bfdname.
-C
--demangle[=style]
Decode (demangle) low-level symbol names into user-level names.
Besides removing any initial underscore prepended by the system,
this makes C++ function names readable. Different compilers have
different mangling styles. The optional demangling style argument
can be used to choose an appropriate demangling style for your
compiler.
-e filename
--exe=filename
Specify the name of the executable for which addresses should be
translated. The default file is a.out.
-f
--functions
Display function names as well as file and line number information.
-s
--basenames
Display only the base of each file name.
-i
--inlines
If the address belongs to a function that was inlined, the source
information for all enclosing scopes back to the first non-inlined
function will also be printed. For example, if "main" inlines
"callee1" which inlines "callee2", and address is from "callee2",
the source information for "callee1" and "main" will also be
printed.
-j
--section
Read offsets relative to the specified section instead of absolute
addresses.
-p
--pretty-print
Make the output more human friendly: each location are printed on
one line. If option -i is specified, lines for all enclosing
scopes are prefixed with (inlined by).
-r
-R
--recurse-limit
--no-recurse-limit
--recursion-limit
--no-recursion-limit
Enables or disables a limit on the amount of recursion performed
whilst demangling strings. Since the name mangling formats allow
for an infinite level of recursion it is possible to create strings
whose decoding will exhaust the amount of stack space available on
the host machine, triggering a memory fault. The limit tries to
prevent this from happening by restricting recursion to 2048 levels
of nesting.
The default is for this limit to be enabled, but disabling it may
be necessary in order to demangle truly complicated names. Note
however that if the recursion limit is disabled then stack
exhaustion is possible and any bug reports about such an event will
be rejected.
The -r option is a synonym for the --no-recurse-limit option. The
-R option is a synonym for the --recurse-limit option.
Note this option is only effective if the -C or --demangle option
has been enabled.
@file
Read command-line options from file. The options read are inserted
in place of the original @file option. If file does not exist, or
cannot be read, then the option will be treated literally, and not
removed.
Options in file are separated by whitespace. A whitespace
character may be included in an option by surrounding the entire
option in either single or double quotes. Any character (including
a backslash) may be included by prefixing the character to be
included with a backslash. The file may itself contain additional
@file options; any such options will be processed recursively.
SEE ALSO
Info entries for binutils.
COPYRIGHT
Copyright (c) 1991-2025 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3 or
any later version published by the Free Software Foundation; with no
Invariant Sections, with no Front-Cover Texts, and with no Back-Cover
Texts. A copy of the license is included in the section entitled "GNU
Free Documentation License".
binutils-2.44 2025-05-12 ADDR2LINE(1)
STRINGS(1) Инструменты разработки GNU STRINGS(1)
NAME
strings - выводит последовательности печатаемых символов в файлах
SYNOPSIS
strings [-afovV] [-min-len]
[-n min-len] [--bytes=min-len]
[-t radix] [--radix=radix]
[-e encoding] [--encoding=encoding]
[-U method] [--unicode=method]
[-] [--all] [--print-file-name]
[-T bfdname] [--target=bfdname]
[-w] [--include-all-whitespace]
[-s] [--output-separator sep_string]
[--help] [--version] file...
DESCRIPTION
Для каждого указанного файла GNU strings выводит последовательности
печатаемых символов, которые имеют длину не менее 4 символов (или
указанное число с помощью опций ниже) и за которыми следует непечатаемый
символ.
В зависимости от конфигурации программы strings по умолчанию она может
выводить все найденные последовательности печатаемых символов в каждом
файле или только те, которые находятся в загружаемых, инициализированных
разделах данных. Если тип файла не распознаётся или strings читает из
stdin, то она всегда выводит все найденные последовательности
печатаемых символов.
Для обеспечения обратной совместимости любой файл, указанный после
командной строки с опцией "-", будет сканироваться полностью,
независимо от наличия опции -d.
strings в основном полезна для определения содержимого нефайловых
текстовых файлов.
OPTIONS
-a
--all
- Просканировать весь файл, независимо от того, какие разделы он
содержит или загружаются ли эти разделы и инициализированы. Обычно
это поведение по умолчанию, но strings можно настроить так, чтобы
по умолчанию использовалась опция -d.
Опция - зависит от позиции и заставляет strings выполнять полное
сканирование любого файла, упомянутого после - в командной строке,
даже если указана опция -d.
-d
--data
Выводить строки только из инициализированных, загружаемых разделов
данных в файле. Это может уменьшить количество мусора в выводе, но
также подвергает программу strings возможным уязвимостям в
библиотеке BFD, используемой для сканирования и загрузки разделов.
Strings можно настроить так, чтобы эта опция была поведением по
умолчанию. В таких случаях опция -a может быть использована для
избежания использования библиотеки BFD и вместо этого вывести все
найденные строки в файле.
-f
--print-file-name
Выводить имя файла перед каждой строкой.
--help
Вывести сводку использования программы на стандартный вывод и выйти.
-min-len
-n min-len
--bytes=min-len
Выводить последовательности отображаемых символов, которые имеют
длину не менее min-len символов. Если не указано, используется
значение по умолчанию в 4 символа. Разница между отображаемыми и
неотображаемыми символами зависит от настроек опций -e и -U.
Последовательности всегда завершаются управляющими символами, такими
как перевод строки и возврат каретки, но не символом табуляции.
-o Как -t o. В некоторых других версиях strings опция -o действует как
-t d. Поскольку мы не можем быть совместимыми с обоими вариантами,
мы просто выбрали один.
-t radix
--radix=radix
Выводить смещение в файле перед каждой строкой. Один символ в
аргументе определяет систему счисления смещения — o для восьмеричной,
x для шестнадцатеричной или d для десятичной.
-e encoding
--encoding=encoding
Выбрать кодировку символов для строк, которые нужно найти.
Возможные значения для encoding: s = одиночные 7-битовые байты
(по умолчанию), S = одиночные 8-битовые байты, b = 16-битовые
bigendian, l = 16-битовые littleendian, B = 32-битовые bigendian,
L = 32-битовые littleendian. Полезно для поиска строк с широкими
символами. (l и b применяются, например, к кодировкам Unicode
UTF-16/UCS-2).
-U [d|i|l|e|x|h]
--unicode=[default|invalid|locale|escape|hex|highlight]
Управляет отображением многобайтовых символов, закодированных в
UTF-8, в строках. Значение по умолчанию (--unicode=default) — не
давать им специального обращения и полагаться на настройку опции
--encoding. Другие значения этой опции автоматически включают
--encoding=S.
Опция --unicode=invalid рассматривает их как неграфические символы
и, следовательно, не часть допустимой строки. Все остальные опции
рассматривают их как допустимые символы строк.
Опция --unicode=locale отображает их в текущей локали, которая может
или не может поддерживать кодировку UTF-8. Опция --unicode=hex
отображает их как последовательности шестнадцатеричных байтов в
угловых скобках <>. Опция --unicode=escape отображает их как
последовательности экранирования (\uxxxx), а опция
--unicode=highlight отображает их как последовательности
экранирования, выделенные красным цветом (если это поддерживается
устройством вывода). Цветовое выделение предназначено для привлечения
внимания к наличию последовательностей Unicode, где они могут не
ожидаться.
-T bfdname
--target=bfdname
Указать формат объектного кода, отличный от формата по умолчанию
вашей системы.
-v
-V
--version
Вывести номер версии программы на стандартный вывод и выйти.
-w
--include-all-whitespace
По умолчанию символы табуляции и пробела включаются в отображаемые
строки, но другие символы пробела, такие как переводы строки и
возвраты каретки, не включаются. Опция -w изменяет это так, чтобы
все символы пробела считались частью строки.
-s
--output-separator
По умолчанию строки вывода разделяются новой строкой. Эта опция
позволяет указать любую строку для использования в качестве
разделителя записей вывода. Полезно с --include-all-whitespace, где
строки могут содержать переводы строк внутри.
@file
Читать опции командной строки из файла. Прочитанные опции
вставляются на место оригинальной опции @file. Если файл не существует
или не может быть прочитан, опция будет обработана буквально, без
удаления.
Опции в файле разделяются пробелами. Символ пробела можно включить
в опцию, окружив всю опцию одиночными или двойными кавычками. Любые
символы (включая обратную косую черту) можно включить, предваряя
символ, который нужно включить, обратной косой чертой. Файл может
сам содержать дополнительные опции @file; такие опции будут
обработаны рекурсивно.
SEE ALSO
ar(1), nm(1), objdump(1), ranlib(1), readelf(1) и разделы Info для
binutils.
COPYRIGHT
Copyright (c) 1991-2025 Free Software Foundation, Inc.
Разрешается копировать, распространять и/или изменять этот документ
на условиях Лицензии GNU Free Documentation License, версии 1.3 или
любой более поздней версии, опубликованной Free Software Foundation;
без Инвариантных Разделов, без Текстов на Обложке и без Текстов на
Задней Обложке. Копия лицензии включена в раздел, озаглавленный "GNU
Free Documentation License".
binutils-2.44 2025-05-12 STRINGS(1)
STRINGS(1) GNU Development Tools STRINGS(1)
NAME
strings - print the sequences of printable characters in files
SYNOPSIS
strings [-afovV] [-min-len]
[-n min-len] [--bytes=min-len]
[-t radix] [--radix=radix]
[-e encoding] [--encoding=encoding]
[-U method] [--unicode=method]
[-] [--all] [--print-file-name]
[-T bfdname] [--target=bfdname]
[-w] [--include-all-whitespace]
[-s] [--output-separator sep_string]
[--help] [--version] file...
DESCRIPTION
For each file given, GNU strings prints the printable character
sequences that are at least 4 characters long (or the number given with
the options below) and are followed by an unprintable character.
Depending upon how the strings program was configured it will default
to either displaying all the printable sequences that it can find in
each file, or only those sequences that are in loadable, initialized
data sections. If the file type is unrecognizable, or if strings is
reading from stdin then it will always display all of the printable
sequences that it can find.
For backwards compatibility any file that occurs after a command-line
option of just - will also be scanned in full, regardless of the
presence of any -d option.
strings is mainly useful for determining the contents of non-text
files.
OPTIONS
-a
--all
- Scan the whole file, regardless of what sections it contains or
whether those sections are loaded or initialized. Normally this is
the default behaviour, but strings can be configured so that the -d
is the default instead.
The - option is position dependent and forces strings to perform
full scans of any file that is mentioned after the - on the command
line, even if the -d option has been specified.
-d
--data
Only print strings from initialized, loaded data sections in the
file. This may reduce the amount of garbage in the output, but it
also exposes the strings program to any security flaws that may be
present in the BFD library used to scan and load sections. Strings
can be configured so that this option is the default behaviour. In
such cases the -a option can be used to avoid using the BFD library
and instead just print all of the strings found in the file.
-f
--print-file-name
Print the name of the file before each string.
--help
Print a summary of the program usage on the standard output and
exit.
-min-len
-n min-len
--bytes=min-len
Print sequences of displayable characters that are at least min-len
characters long. If not specified a default minimum length of 4 is
used. The distinction between displayable and non-displayable
characters depends upon the setting of the -e and -U options.
Sequences are always terminated at control characters such as new-
line and carriage-return, but not the tab character.
-o Like -t o. Some other versions of strings have -o act like -t d
instead. Since we can not be compatible with both ways, we simply
chose one.
-t radix
--radix=radix
Print the offset within the file before each string. The single
character argument specifies the radix of the offset---o for octal,
x for hexadecimal, or d for decimal.
-e encoding
--encoding=encoding
Select the character encoding of the strings that are to be found.
Possible values for encoding are: s = single-7-bit-byte characters
(default), S = single-8-bit-byte characters, b = 16-bit bigendian,
l = 16-bit littleendian, B = 32-bit bigendian, L = 32-bit
littleendian. Useful for finding wide character strings. (l and b
apply to, for example, Unicode UTF-16/UCS-2 encodings).
-U [d|i|l|e|x|h]
--unicode=[default|invalid|locale|escape|hex|highlight]
Controls the display of UTF-8 encoded multibyte characters in
strings. The default (--unicode=default) is to give them no
special treatment, and instead rely upon the setting of the
--encoding option. The other values for this option automatically
enable --encoding=S.
The --unicode=invalid option treats them as non-graphic characters
and hence not part of a valid string. All the remaining options
treat them as valid string characters.
The --unicode=locale option displays them in the current locale,
which may or may not support UTF-8 encoding. The --unicode=hex
option displays them as hex byte sequences enclosed between <>
characters. The --unicode=escape option displays them as escape
sequences (\uxxxx) and the --unicode=highlight option displays them
as escape sequences highlighted in red (if supported by the output
device). The colouring is intended to draw attention to the
presence of unicode sequences where they might not be expected.
-T bfdname
--target=bfdname
Specify an object code format other than your system's default
format.
-v
-V
--version
Print the program version number on the standard output and exit.
-w
--include-all-whitespace
By default tab and space characters are included in the strings
that are displayed, but other whitespace characters, such a
newlines and carriage returns, are not. The -w option changes this
so that all whitespace characters are considered to be part of a
string.
-s
--output-separator
By default, output strings are delimited by a new-line. This option
allows you to supply any string to be used as the output record
separator. Useful with --include-all-whitespace where strings may
contain new-lines internally.
@file
Read command-line options from file. The options read are inserted
in place of the original @file option. If file does not exist, or
cannot be read, then the option will be treated literally, and not
removed.
Options in file are separated by whitespace. A whitespace
character may be included in an option by surrounding the entire
option in either single or double quotes. Any character (including
a backslash) may be included by prefixing the character to be
included with a backslash. The file may itself contain additional
@file options; any such options will be processed recursively.
SEE ALSO
ar(1), nm(1), objdump(1), ranlib(1), readelf(1) and the Info entries
for binutils.
COPYRIGHT
Copyright (c) 1991-2025 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3 or
any later version published by the Free Software Foundation; with no
Invariant Sections, with no Front-Cover Texts, and with no Back-Cover
Texts. A copy of the license is included in the section entitled "GNU
Free Documentation License".
binutils-2.44 2025-05-12 STRINGS(1)
OBJCOPY(1) Инструменты разработки GNU OBJCOPY(1)
NAME
objcopy - копировать и переводить объектные файлы
SYNOPSIS
objcopy [-F bfdname|--target=bfdname]
[-I bfdname|--input-target=bfdname]
[-O bfdname|--output-target=bfdname]
[-B bfdarch|--binary-architecture=bfdarch]
[-S|--strip-all]
[-g|--strip-debug]
[--strip-unneeded]
[-K symbolname|--keep-symbol=symbolname]
[--keep-file-symbols]
[--keep-section-symbols]
[-N symbolname|--strip-symbol=symbolname]
[--strip-unneeded-symbol=symbolname]
[-G symbolname|--keep-global-symbol=symbolname]
[--localize-hidden]
[-L symbolname|--localize-symbol=symbolname]
[--globalize-symbol=symbolname]
[--globalize-symbols=filename]
[-W symbolname|--weaken-symbol=symbolname]
[-w|--wildcard]
[-x|--discard-all]
[-X|--discard-locals]
[-b byte|--byte=byte]
[-i [breadth]|--interleave[=breadth]]
[--interleave-width=width]
[-j sectionpattern|--only-section=sectionpattern]
[-R sectionpattern|--remove-section=sectionpattern]
[--keep-section=sectionpattern]
[--remove-relocations=sectionpattern]
[--strip-section-headers]
[-p|--preserve-dates]
[-D|--enable-deterministic-archives]
[-U|--disable-deterministic-archives]
[--debugging]
[--gap-fill=val]
[--pad-to=address]
[--set-start=val]
[--adjust-start=incr]
[--change-addresses=incr]
[--change-section-address sectionpattern{=,+,-}val]
[--change-section-lma sectionpattern{=,+,-}val]
[--change-section-vma sectionpattern{=,+,-}val]
[--change-warnings] [--no-change-warnings]
[--set-section-flags sectionpattern=flags]
[--set-section-alignment sectionpattern=align]
[--add-section sectionname=filename]
[--dump-section sectionname=filename]
[--update-section sectionname=filename]
[--rename-section oldname=newname[,flags]]
[--long-section-names {enable,disable,keep}]
[--change-leading-char] [--remove-leading-char]
[--reverse-bytes=num]
[--srec-len=ival] [--srec-forceS3]
[--redefine-sym old=new]
[--redefine-syms=filename]
[--weaken]
[--keep-symbols=filename]
[--strip-symbols=filename]
[--strip-unneeded-symbols=filename]
[--keep-global-symbols=filename]
[--localize-symbols=filename]
[--weaken-symbols=filename]
[--add-symbol name=[section:]value[,flags]]
[--alt-machine-code=index]
[--prefix-symbols=string]
[--prefix-sections=string]
[--prefix-alloc-sections=string]
[--add-gnu-debuglink=path-to-file]
[--only-keep-debug]
[--strip-dwo]
[--extract-dwo]
[--extract-symbol]
[--writable-text]
[--readonly-text]
[--pure]
[--impure]
[--file-alignment=num]
[--heap=reserve[,commit]]
[--image-base=address]
[--section-alignment=num]
[--stack=reserve[,commit]]
[--subsystem=which:major.minor]
[--compress-debug-sections]
[--decompress-debug-sections]
[--elf-stt-common=val]
[--merge-notes]
[--no-merge-notes]
[--verilog-data-width=val]
[-v|--verbose]
[-V|--version]
[--help] [--info]
infile [outfile]
DESCRIPTION
Утилита GNU objcopy копирует содержимое объектного файла в другой. objcopy использует библиотеку GNU BFD для чтения и записи объектных файлов. Она может записывать файл назначения в формате, отличном от формата исходного объектного файла. Точное поведение objcopy управляется опциями командной строки. Обратите внимание, что objcopy должна уметь копировать полностью связанный файл между любыми двумя форматами. Однако копирование позиционируемого объектного файла между любыми двумя форматами может не работать так, как ожидается.
objcopy создаёт временные файлы для выполнения переводов и удаляет их после. objcopy использует BFD для всей работы по переводу; у неё есть доступ ко всем форматам, описанным в BFD, и поэтому она может распознавать большинство форматов без явного указания.
objcopy можно использовать для генерации S-records, указав целевой формат srec (например, используйте -O srec).
objcopy можно использовать для генерации сырого бинарного файла, указав целевой формат binary (например, используйте -O binary). При генерации сырого бинарного файла objcopy в основном создаст дамп памяти содержимого входного объектного файла. Все символы и информация о релокациях будут отброшены. Дамп памяти начнётся с адреса загрузки самой низкой секции, скопированной в выходной файл.
При генерации S-record или сырого бинарного файла может быть полезно использовать -S для удаления секций, содержащих информацию отладки. В некоторых случаях -R будет полезна для удаления секций, которые содержат информацию, не нужную для бинарного файла.
Обратите внимание — objcopy не может изменить порядок байтов в своих входных файлах. Если формат входных файлов имеет порядок байтов (некоторые форматы не имеют), objcopy может копировать входные файлы только в форматы файлов, которые имеют тот же порядок байтов или не имеют порядка байтов (например, srec). (Однако см. опцию --reverse-bytes.)
OPTIONS
infile
outfile
Входной и выходной файлы соответственно. Если outfile не указан, objcopy создаст временный файл и деструктивно переименует результат с именем infile.
-I bfdname
--input-target=bfdname
Рассматривать формат объекта исходного файла как bfdname, а не пытаться вывести его.
-O bfdname
--output-target=bfdname
Записывать выходной файл с использованием формата объекта bfdname.
-F bfdname
--target=bfdname
Использовать bfdname в качестве формата объекта как для входного, так и для выходного файла; т.е. просто перенести данные из источника в место назначения без перевода.
-B bfdarch
--binary-architecture=bfdarch
Полезно при преобразовании файла без архитектуры в объектный файл. В этом случае архитектуру вывода можно установить как bfdarch. Эта опция будет игнорироваться, если входной файл имеет известную bfdarch. Вы можете получить доступ к этим бинарным данным внутри программы, ссылаясь на специальные символы, создаваемые процессом преобразования. Эти символы называются _binary_objfile_start, _binary_objfile_end и _binary_objfile_size. Например, вы можете преобразовать файл изображения в объектный файл и затем получить к нему доступ в коде с помощью этих символов.
-j sectionpattern
--only-section=sectionpattern
Копировать только указанные секции из входного файла в выходной файл. Эта опция может быть указана несколько раз. Обратите внимание, что использование этой опции неподходящим образом может сделать выходной файл непригодным для использования. В sectionpattern допускаются символы подстановки.
Если первым символом sectionpattern является восклицательный знак (!), то соответствующие секции не будут скопированы, даже если более раннее использование --only-section в той же командной строке могло бы скопировать их. Например:
--only-section=.text.* --only-section=!.text.foo
скопирует все секции, соответствующие '.text.*', но не секцию '.text.foo'.
-R sectionpattern
--remove-section=sectionpattern
Удалить любые секции, соответствующие sectionpattern, из выходного файла. Эта опция может быть указана несколько раз. Обратите внимание, что использование этой опции неподходящим образом может сделать выходной файл непригодным для использования. В sectionpattern допускаются символы подстановки. Использование опций -j и -R вместе приводит к неопределённому поведению.
Если первым символом sectionpattern является восклицательный знак (!), то соответствующие секции не будут удалены, даже если более раннее использование --remove-section в той же командной строке могло бы удалить их. Например:
--remove-section=.text.* --remove-section=!.text.foo
удалит все секции, соответствующие шаблону '.text.*', но не удалит секцию '.text.foo'.
--keep-section=sectionpattern
При удалении секций из выходного файла сохранять секции, соответствующие sectionpattern.
--remove-relocations=sectionpattern
Удалить нединамические релокации из выходного файла для любой секции, соответствующей sectionpattern. Эта опция может быть указана несколько раз. Обратите внимание, что использование этой опции неподходящим образом может сделать выходной файл непригодным для использования, и попытка удалить динамическую секцию релокаций, такую как .rela.plt, из исполняемого файла или разделяемой библиотеки с --remove-relocations=.plt не сработает. В sectionpattern допускаются символы подстановки. Например:
--remove-relocations=.text.*
удалит релокации для всех секций, соответствующих шаблону '.text.*'.
Если первым символом sectionpattern является восклицательный знак (!), то соответствующие секции не будут иметь удалённых релокаций, даже если более раннее использование --remove-relocations в той же командной строке могло бы удалить их. Например:
--remove-relocations=.text.* --remove-relocations=!.text.foo
удалит все релокации для секций, соответствующих шаблону '.text.*', но не удалит релокации для секции '.text.foo'.
--strip-section-headers
Удалить заголовки секций. Эта опция специфична для ELF-файлов. Подразумевает --strip-all и --merge-notes.
-S
--strip-all
Не копировать информацию о релокациях и символах из исходного файла. Также удаляет секции отладки.
-g
--strip-debug
Не копировать символы и секции отладки из исходного файла.
--strip-unneeded
Удалить все символы, которые не нужны для обработки релокаций, помимо символов и секций отладки, удаляемых --strip-debug.
-K symbolname
--keep-symbol=symbolname
При удалении символов сохранять символ symbolname, даже если он обычно удаляется. Эта опция может быть указана несколько раз.
-N symbolname
--strip-symbol=symbolname
Не копировать символ symbolname из исходного файла. Эта опция может быть указана несколько раз.
--strip-unneeded-symbol=symbolname
Не копировать символ symbolname из исходного файла, если он не нужен для релокации. Эта опция может быть указана несколько раз.
-G symbolname
--keep-global-symbol=symbolname
Сохранить только символ symbolname как глобальный. Сделать все другие символы локальными для файла, чтобы они не были видны извне. Эта опция может быть указана несколько раз. Обратите внимание: эта опция не может использоваться вместе с опциями --globalize-symbol или --globalize-symbols.
--localize-hidden
В ELF-объекте пометить все символы с скрытой или внутренней видимостью как локальные. Эта опция применяется поверх опций локализации, специфичных для символов, таких как -L.
-L symbolname
--localize-symbol=symbolname
Преобразовать глобальный или слабый символ с именем symbolname в локальный символ, чтобы он не был виден извне. Эта опция может быть указана несколько раз. Обратите внимание — уникальные символы не преобразуются.
-W symbolname
--weaken-symbol=symbolname
Сделать символ symbolname слабым. Эта опция может быть указана несколько раз.
--globalize-symbol=symbolname
Придать символу symbolname глобальную область видимости, чтобы он был видим извне файла, в котором он определён. Эта опция может быть указана несколько раз. Обратите внимание: эта опция не может использоваться вместе с опциями -G или --keep-global-symbol.
-w
--wildcard
Разрешить регулярные выражения в именах символов, используемых в других опциях командной строки. Операторы вопросительного знака (?), звёздочки (*), обратной косой черты (\) и квадратных скобок ([]) можно использовать в любом месте имени символа. Если первым символом имени символа является восклицательный знак (!), то смысл переключателя инвертируется для этого символа. Например:
-w -W !foo -W fo*
заставит objcopy ослабить все символы, начинающиеся с "fo", кроме символа "foo".
-x
--discard-all
Не копировать неглобальные символы из исходного файла.
-X
--discard-locals
Не копировать локальные символы, генерируемые компилятором. (Они обычно начинаются с L или ..)
-b byte
--byte=byte
Если чересстрочное переплетение включено с помощью опции --interleave, то начать диапазон байтов для сохранения с byte-го байта. byte может быть в диапазоне от 0 до breadth-1, где breadth — значение, указанное опцией --interleave.
-i [breadth]
--interleave[=breadth]
Копировать только диапазон из каждых breadth байтов. (Данные заголовка не затрагиваются). Выбрать, с какого байта в диапазоне начинается копирование, с помощью опции --byte. Выбрать ширину диапазона с помощью опции --interleave-width.
Эта опция полезна для создания файлов для программирования ROM. Она обычно используется с целевым форматом "srec". Обратите внимание, что objcopy выдаст предупреждение, если вы не укажете опцию --byte.
Значение breadth по умолчанию — 4, так что с --byte, установленным в 0, objcopy скопирует первый байт из каждых четырёх байтов из входного файла в выходной.
--interleave-width=width
При использовании с опцией --interleave копировать width байтов за раз. Начало диапазона байтов для копирования устанавливается опцией --byte, а размер диапазона — опцией --interleave.
Значение по умолчанию для этой опции — 1. Значение width плюс значение byte, установленное опцией --byte, не должно превышать breadth, установленное опцией --interleave.
Эта опция может быть использована для создания образов для двух 16-битных флеш-памятей, чересстрочно переплетённых в 32-битной шине, путём передачи -b 0 -i 4 --interleave-width=2 и -b 2 -i 4 --interleave-width=2 двум командам objcopy. Если вход был '12345678', то выходы будут '1256' и '3478' соответственно.
-p
--preserve-dates
Установить даты доступа и модификации выходного файла такими же, как у входного файла.
Эта опция также копирует дату, хранящуюся в заголовке файла формата PE, если переменная окружения SOURCE_DATE_EPOCH не определена. Если она определена, то эта переменная будет использоваться как дата, хранящаяся в заголовке, интерпретируемая как количество секунд с эпохи Unix.
-D
--enable-deterministic-archives
Работать в детерминированном режиме. При копировании членов архива и записи индекса архива использовать ноль для UID, GID, временных меток и использовать последовательные режимы файлов для всех файлов.
Если binutils был настроен с --enable-deterministic-archives, то этот режим включён по умолчанию. Его можно отключить с помощью опции -U, ниже.
-U
--disable-deterministic-archives
Не работать в детерминированном режиме. Это обратное -D: при копировании членов архива и записи индекса архива использовать их фактические значения UID, GID, временных меток и режимов файлов.
Это значение по умолчанию, если binutils не был настроен с --enable-deterministic-archives.
--debugging
Преобразовать информацию отладки, если возможно. Это не значение по умолчанию, потому что поддерживаются только определённые форматы отладки, и процесс преобразования может быть времязатратным.
--gap-fill val
Заполнить пробелы между секциями значением val. Это применяется к адресу загрузки (LMA) секций. Это достигается путём увеличения размера секции с более низким адресом и заполнения созданного дополнительного пространства значением val.
--pad-to address
Дополнить выходной файл до адреса загрузки address. Это достигается путём увеличения размера последней секции. Дополнительное пространство заполняется значением, указанным --gap-fill (по умолчанию ноль).
--set-start val
Установить адрес начала (также известный как адрес входа) нового файла как val. Не все форматы объектных файлов поддерживают установку адреса начала.
--change-start incr
--adjust-start incr
Изменить адрес начала (также известный как адрес входа), добавив incr. Не все форматы объектных файлов поддерживают установку адреса начала.
--change-addresses incr
--adjust-vma incr
Изменить адреса VMA и LMA всех секций, а также адрес начала, добавив incr. Некоторые форматы объектных файлов не позволяют изменять адреса секций произвольно. Обратите внимание, что это не релокация секций; если программа ожидает, что секции будут загружены по определённому адресу, а эта опция используется для изменения секций так, чтобы они загружались по другому адресу, программа может не сработать.
--change-section-address sectionpattern{=,+,-}val
--adjust-section-vma sectionpattern{=,+,-}val
Установить или изменить адреса VMA и LMA любой секции, соответствующей sectionpattern. Если используется =, адрес секции устанавливается как val. В противном случае val добавляется к адресу секции или вычитается из него. См. комментарии под --change-addresses выше. Если sectionpattern не соответствует ни одной секции во входном файле, будет выдано предупреждение, если не используется --no-change-warnings.
--change-section-lma sectionpattern{=,+,-}val
Установить или изменить адрес LMA любой секции, соответствующей sectionpattern. Адрес LMA — это адрес, по которому секция будет загружена в память при запуске программы. Обычно это то же самое, что и адрес VMA, который является адресом секции во время выполнения программы, но в некоторых системах, особенно где программа хранится в ROM, они могут отличаться. Если используется =, адрес секции устанавливается как val. В противном случае val добавляется к адресу секции или вычитается из него. См. комментарии под --change-addresses выше. Если sectionpattern не соответствует ни одной секции во входном файле, будет выдано предупреждение, если не используется --no-change-warnings.
--change-section-vma sectionpattern{=,+,-}val
Установить или изменить адрес VMA любой секции, соответствующей sectionpattern. Адрес VMA — это адрес, по которому секция будет расположена после запуска выполнения программы. Обычно это то же самое, что и адрес LMA, который является адресом, по которому секция будет загружена в память, но в некоторых системах, особенно где программа хранится в ROM, они могут отличаться. Если используется =, адрес секции устанавливается как val. В противном случае val добавляется к адресу секции или вычитается из него. См. комментарии под --change-addresses выше. Если sectionpattern не соответствует ни одной секции во входном файле, будет выдано предупреждение, если не используется --no-change-warnings.
Обратите внимание — изменение VMA секций в полностью связанном бинарном файле может быть опасным, поскольку там может быть код, который ожидает, что секции будут расположены по их старому адресу.
--change-warnings
--adjust-warnings
Если используется --change-section-address, --change-section-lma или --change-section-vma, и шаблон секции не соответствует ни одной секции, выдать предупреждение. Это значение по умолчанию.
--no-change-warnings
--no-adjust-warnings
Не выдавать предупреждение, если используется --change-section-address, --change-section-lma или --change-section-vma, даже если шаблон секции не соответствует ни одной секции.
--set-section-flags sectionpattern=flags
Установить флаги для любой секции, соответствующей sectionpattern. Аргумент flags — это строка, разделённая запятыми, имён флагов. Распознаваемые имена — alloc, contents, load, noload, readonly, code, data, rom, exclude, share, debug и large. Вы можете установить флаг contents для секции, у которой нет содержимого, но бессмысленно сбрасывать флаг contents для секции, у которой есть содержимое — просто удалите секцию. Не все флаги имеют смысл для всех форматов объектных файлов. В частности, флаг share имеет смысл только для файлов формата COFF, а не для файлов формата ELF. Флаг large, специфичный для ELF x86-64, соответствует SHF_X86_64_LARGE.
--set-section-alignment sectionpattern=align
Установить выравнивание для любой секции, соответствующей sectionpattern. align указывает выравнивание в байтах и должно быть степенью двойки, т.е. 1, 2, 4, 8 и т.д.
Обратите внимание — установка выравнивания секции не автоматически выровняет её адреса LMA или VMA. Если они также нуждаются в изменении, то должны быть использованы опции --change-section-lma и/или --change-section-vma. Также обратите внимание, что изменение VMA может вызвать проблемы в полностью связанных бинарных файлах, где может быть код, который ожидает, что содержимое секций будет расположено по их старому адресу.
--add-section sectionname=filename
Добавить новую секцию с именем sectionname при копировании файла. Содержимое новой секции берётся из файла filename. Размер секции будет равен размеру файла. Эта опция работает только с форматами файлов, которые могут поддерживать секции с произвольными именами. Обратите внимание — может потребоваться использовать опцию --set-section-flags для установки атрибутов newly created секции.
--dump-section sectionname=filename
Поместить содержимое секции с именем sectionname в файл filename, перезаписав любое содержимое, которое могло быть там ранее. Эта опция является обратной --add-section. Эта опция похожа на опцию --only-section, за исключением того, что она не создаёт отформатированный файл, а просто дампит содержимое как сырые бинарные данные, без применения каких-либо релокаций. Опция может быть указана несколько раз.
--update-section sectionname=filename
Заменить существующее содержимое секции с именем sectionname на содержимое файла filename. Размер секции будет скорректирован до размера файла. Флаги секции для sectionname останутся неизменными. Для файлов формата ELF сопоставление секций сегментам также останется неизменным, что невозможно с помощью --remove-section, за которой следует --add-section. Опция может быть указана несколько раз.
Обратите внимание — возможно использовать --rename-section и --update-section для одновременного обновления и переименования секции из одной командной строки. В этом случае передайте исходное имя секции в --update-section и исходное и новое имя секции в --rename-section.
--add-symbol name=[section:]value[,flags]
Добавить новый символ с именем name при копировании файла. Эта опция может быть указана несколько раз. Если секция указана, символ будет ассоциирован с ней и будет относительным к ней, в противном случае это будет символ ABS. Указание неопределённой секции приведёт к фатальной ошибке. Для значения проверки нет, оно будет взято как указано. Флаги символа могут быть указаны, и не все флаги будут иметь смысл для всех форматов объектных файлов. По умолчанию символ будет глобальным. Специальный флаг 'before=othersym' вставит новый символ перед указанным othersym, в противном случае символ(ы) будут добавлены в конец таблицы символов в порядке их появления.
--rename-section oldname=newname[,flags]
Переименовать секцию из oldname в newname, при необходимости изменив флаги секции на flags. Это имеет преимущество перед использованием скрипта линкера для переименования, поскольку выход остаётся объектным файлом и не становится связанным исполняемым файлом. Эта опция принимает те же флаги, что и опция --set-section-flags.
Эта опция особенно полезна, когда формат входа — binary, поскольку это всегда создаст секцию с именем .data. Если, например, вы хотели вместо этого создать секцию с именем .rodata, содержащую бинарные данные, вы могли бы использовать следующую командную строку для достижения этого:
objcopy -I binary -O <output_format> -B <architecture> \
--rename-section .data=.rodata,alloc,load,readonly,data,contents \
<input_binary_file> <output_object_file>
--long-section-names {enable,disable,keep}
Управляет обработкой длинных имён секций при обработке форматов "COFF" и "PE-COFF". Поведение по умолчанию, keep, заключается в сохранении длинных имён секций, если они присутствуют во входном файле. Опции enable и disable принудительно включают или отключают использование длинных имён секций в выходном объекте; при disable любые длинные имена секций во входном объекте будут усечены. Опция enable будет генерировать длинные имена секций только если они присутствуют во входных данных; это в основном то же самое, что и keep, но не определено, может ли опция enable принудительно создать пустую таблицу строк в выходном файле.
--change-leading-char
Некоторые форматы объектных файлов используют специальные символы в начале символов. Наиболее распространённый такой символ — подчёркивание, которое компиляторы часто добавляют перед каждым символом. Эта опция говорит objcopy изменить начальный символ каждого символа при преобразовании между форматами объектных файлов. Если форматы объектных файлов используют один и тот же начальный символ, эта опция не имеет эффекта. В противном случае она добавит символ, удалит символ или изменит символ, в зависимости от ситуации.
--remove-leading-char
Если первым символом глобального символа является специальный начальный символ, используемый форматом объектного файла, удалить этот символ. Наиболее распространённый начальный символ — подчёркивание. Эта опция удалит начальное подчёркивание из всех глобальных символов. Это может быть полезно, если вы хотите связать объекты разных форматов файлов с разными конвенциями имён символов. Это отличается от --change-leading-char, потому что всегда изменяет имя символа, когда это уместно, независимо от формата объектного файла выходного файла.
--reverse-bytes=num
Обратить байты в секции с выходным содержимым. Длина секции должна быть чётно делимой на значение, указанное, чтобы обмен мог произойти. Обратное происходит перед выполнением чересстрочного переплетения.
Эта опция обычно используется при генерации образов ROM для проблемных целевых систем. Например, на некоторых целевых платах 32-битные слова, извлечённые из 8-битных ROM, собираются в порядке байтов little-endian независимо от порядка байтов CPU. В зависимости от модели программирования порядок байтов ROM может потребовать изменения.
Рассмотрите простой файл с секцией, содержащей следующие восемь байтов: 12345678.
Использование --reverse-bytes=2 для приведённого выше примера упорядочит байты в выходном файле как 21436587.
Использование --reverse-bytes=4 для приведённого выше примера упорядочит байты в выходном файле как 43218765.
Использование --reverse-bytes=2 для приведённого выше примера, за которым следует --reverse-bytes=4 для выходного файла, упорядочит байты во втором выходном файле как 34127856.
--srec-len=ival
Имеет смысл только для вывода srec. Установить максимальную длину Srecords, которые производятся, равной ival. Эта длина охватывает поля адреса, данных и crc.
--srec-forceS3
Имеет смысл только для вывода srec. Избегать генерации записей S1/S2, создавая только формат записей S3.
--redefine-sym old=new
Изменить имя символа old на new. Это может быть полезно, когда вы пытаетесь связать два объекта вместе, у которых нет исходного кода, и есть коллизии имён.
--redefine-syms=filename
Применить --redefine-sym к каждой паре символов "old new", перечисленной в файле filename. filename — это просто плоский файл с одной парой символов на строку. Комментарии строк могут быть введены символом хэша. Эта опция может быть указана несколько раз.
--weaken
Сделать все глобальные символы в файле слабыми. Это может быть полезно при сборке объекта, который будет связан с другими объектами с помощью опции -R линкера. Эта опция эффективна только при использовании формата объектного файла, который поддерживает слабые символы.
--keep-symbols=filename
Применить опцию --keep-symbol к каждому символу, перечисленному в файле filename. filename — это просто плоский файл с одним именем символа на строку. Комментарии строк могут быть введены символом хэша. Эта опция может быть указана несколько раз.
--strip-symbols=filename
Применить опцию --strip-symbol к каждому символу, перечисленному в файле filename. filename — это просто плоский файл с одним именем символа на строку. Комментарии строк могут быть введены символом хэша. Эта опция может быть указана несколько раз.
--strip-unneeded-symbols=filename
Применить опцию --strip-unneeded-symbol к каждому символу, перечисленному в файле filename. filename — это просто плоский файл с одним именем символа на строку. Комментарии строк могут быть введены символом хэша. Эта опция может быть указана несколько раз.
--keep-global-symbols=filename
Применить опцию --keep-global-symbol к каждому символу, перечисленному в файле filename. filename — это просто плоский файл с одним именем символа на строку. Комментарии строк могут быть введены символом хэша. Эта опция может быть указана несколько раз.
--localize-symbols=filename
Применить опцию --localize-symbol к каждому символу, перечисленному в файле filename. filename — это просто плоский файл с одним именем символа на строку. Комментарии строк могут быть введены символом хэша. Эта опция может быть указана несколько раз.
--globalize-symbols=filename
Применить опцию --globalize-symbol к каждому символу, перечисленному в файле filename. filename — это просто плоский файл с одним именем символа на строку. Комментарии строк могут быть введены символом хэша. Эта опция может быть указана несколько раз. Обратите внимание: эта опция не может использоваться вместе с опциями -G или --keep-global-symbol.
--weaken-symbols=filename
Применить опцию --weaken-symbol к каждому символу, перечисленному в файле filename. filename — это просто плоский файл с одним именем символа на строку. Комментарии строк могут быть введены символом хэша. Эта опция может быть указана несколько раз.
--alt-machine-code=index
Если архитектура вывода имеет альтернативные машинные коды, использовать index-й код вместо кода по умолчанию. Это полезно в случае, если машине присвоен официальный код, а инструментальная цепочка принимает новый код, но другие приложения всё ещё зависят от использования исходного кода. Для архитектур на основе ELF, если альтернативный индекс не существует, значение трактуется как абсолютное число для хранения в поле e_machine заголовка ELF.
--writable-text
Пометить выходной текст как записываемый. Эта опция не имеет смысла для всех форматов объектных файлов.
--readonly-text
Сделать выходной текст защищённым от записи. Эта опция не имеет смысла для всех форматов объектных файлов.
--pure
Пометить выходной файл как запрашиваемый по требованию. Эта опция не имеет смысла для всех форматов объектных файлов.
--impure
Пометить выходной файл как нечистый. Эта опция не имеет смысла для всех форматов объектных файлов.
--prefix-symbols=string
Добавить префикс string ко всем символам в выходном файле.
--prefix-sections=string
Добавить префикс string ко всем именам секций в выходном файле.
--prefix-alloc-sections=string
Добавить префикс string ко всем именам выделенных секций в выходном файле.
--add-gnu-debuglink=path-to-file
Создать секцию .gnu_debuglink, которая содержит ссылку на path-to-file, и добавить её в выходной файл. Обратите внимание: файл по пути path-to-file должен существовать. Часть процесса добавления секции .gnu_debuglink включает вложение контрольной суммы содержимого файла отладочной информации в секцию.
Если файл отладочной информации строится в одном месте, но будет установлен позже в другом месте, то не используйте путь к установленному месту. Опция --add-gnu-debuglink не сработает, потому что установленный файл ещё не существует. Вместо этого поместите файл отладочной информации в текущий каталог и используйте опцию --add-gnu-debuglink без каких-либо компонентов каталога, как в этом примере:
objcopy --add-gnu-debuglink=foo.debug
Во время отладки отладчик попытается найти отдельный файл отладочной информации в наборе известных мест. Точный набор этих мест варьируется в зависимости от используемой дистрибуции, но обычно включает:
"* Тот же каталог, что и исполняемый файл."
"* Подкаталог каталога, содержащего исполняемый файл,"
называемый .debug
"* Глобальный каталог отладки, такой как /usr/lib/debug."
Пока файл отладочной информации установлен в одно из этих мест перед запуском отладчика, всё должно работать правильно.
--keep-section-symbols
При удалении файла, возможно с --strip-debug или --strip-unneeded, сохранять любые символы, указывающие имена секций, которые в противном случае будут удалены.
--keep-file-symbols
При удалении файла, возможно с --strip-debug или --strip-unneeded, сохранять любые символы, указывающие имена исходных файлов, которые в противном случае будут удалены.
--only-keep-debug
Удалить файл, удаляя содержимое любых секций, которые не будут удалены --strip-debug, и оставляя секции отладки нетронутыми. В ELF-файлах это сохраняет все секции заметок в выходе.
Обратите внимание — заголовки секций удалённых секций сохраняются, включая их размеры, но содержимое секции отбрасывается. Заголовки секций сохраняются, чтобы другие инструменты могли сопоставить файл отладочной информации с реальным исполняемым файлом, даже если этот исполняемый файл был релокационирован в другое адресное пространство.
Цель — использовать эту опцию вместе с --add-gnu-debuglink для создания двухчастного исполняемого файла. Один — это очищенный бинарный файл, который будет занимать меньше места в RAM и в дистрибуции, а второй — файл отладочной информации, который нужен только если требуются возможности отладки. Предлагаемая процедура создания этих файлов следующая:
1.<Составьте исполняемый файл как обычно. Предполагая, что он называется>
"foo" then...
1.<Выполните "objcopy --only-keep-debug foo foo.dbg" для>
создания файла, содержащего информацию отладки.
1.<Выполните "objcopy --strip-debug foo" для создания>
очищенного исполняемого файла.
1.<Выполните "objcopy --add-gnu-debuglink=foo.dbg foo">
для добавления ссылки на информацию отладки в очищенный
исполняемый файл.
Обратите внимание — выбор ".dbg" в качестве расширения для файла отладочной информации произвольный. Также шаг "--only-keep-debug" необязателен. Вы могли бы вместо этого сделать это:
1.<Составьте исполняемый файл как обычно.>
1.<Скопируйте "foo" в "foo.full">
1.<Выполните "objcopy --strip-debug foo">
1.<Выполните "objcopy --add-gnu-debuglink=foo.full foo">
т.е. файл, на который указывает --add-gnu-debuglink, может быть полным исполняемым файлом. Он не обязательно должен быть файлом, созданным переключателем --only-keep-debug.
Обратите внимание — этот переключатель предназначен только для использования с полностью связанными файлами. Не имеет смысла использовать его для объектных файлов, где информация отладки может быть неполной. Кроме того, функция gnu_debuglink в настоящее время поддерживает наличие только одного имени файла с информацией отладки, а не нескольких имён на основе одного файла на объект.
--strip-dwo
Удалить содержимое всех секций DWARF .dwo, оставив остальные секции отладки и все символы нетронутыми. Эта опция предназначена для использования компилятором как часть опции -gsplit-dwarf, которая разделяет информацию отладки между .o-файлом и отдельным .dwo-файлом. Компилятор генерирует всю информацию отладки в одном файле, затем использует опцию --extract-dwo для копирования секций .dwo в .dwo-файл, а затем опцию --strip-dwo для удаления этих секций из исходного .o-файла.
--extract-dwo
Извлечь содержимое всех секций DWARF .dwo. См. опцию --strip-dwo для получения дополнительной информации.
--file-alignment num
Указать выравнивание файла. Секции в файле всегда будут начинаться по смещениям файла, которые являются кратными этому числу. Это значение по умолчанию — 512. [Эта опция специфична для целей PE.]
--heap reserve
--heap reserve,commit
Указать количество байтов памяти для резервирования (и, при необходимости, фиксации) для использования в качестве кучи для этой программы. [Эта опция специфична для целей PE.]
--image-base value
Использовать value в качестве базового адреса вашей программы или dll. Это самый низкий адрес памяти, который будет использоваться при загрузке вашей программы или dll. Чтобы уменьшить необходимость релокации и улучшить производительность dll, каждая из них должна иметь уникальный базовый адрес и не пересекаться с другими dll. Значение по умолчанию — 0x400000 для исполняемых файлов и 0x10000000 для dll. [Эта опция специфична для целей PE.]
--section-alignment num
[Эта опция специфична для целей PE.]
Устанавливает поле выравнивания секций в заголовке PE — если оно присутствует в бинарном файле. Секции в памяти всегда будут начинаться по адресам, которые являются кратными этому числу. Значение по умолчанию — 0x1000.
Обратите внимание — эта опция также установит поле выравнивания в флагах каждой секции.
Обратите внимание — если адреса LMA или VMA секции больше не выровнены, и эти адреса не были установлены с помощью опций --set-section-lma или --set-section-vma, и файл был полностью релокационирован, то будет выдано предупредительное сообщение. Тогда будет зависеть от пользователя решить, нужно ли обновлять LMA и VMA.
--stack reserve
--stack reserve,commit
Указать количество байтов памяти для резервирования (и, при необходимости, фиксации) для использования в качестве стека для этой программы. [Эта опция специфична для целей PE.]
--subsystem which
--subsystem which:major
--subsystem which:major.minor
Указать подсистему, под которой будет выполняться ваша программа. Допустимые значения для which — "native", "windows", "console", "posix", "efi-app", "efi-bsd", "efi-rtd", "sal-rtd" и "xbox". Вы также можете опционально установить версию подсистемы. Числовые значения также принимаются для which. [Эта опция специфична для целей PE.]
--extract-symbol
Сохранить флаги секций и символы файла, но удалить все данные секций. В частности, опция:
*<удаляет содержимое всех секций;>
*<устанавливает размер каждой секции в ноль; и>
*<устанавливает начальный адрес файла в ноль.>
Эта опция используется для создания .sym-файла для ядра VxWorks. Она также может быть полезным способом уменьшения размера входного файла линкера --just-symbols.
--compress-debug-sections
Сжать секции DWARF отладки с помощью zlib с SHF_COMPRESSED из ELF ABI. Обратите внимание — если сжатие фактически сделает секцию больше, то она не сжимается.
--compress-debug-sections=none
--compress-debug-sections=zlib
--compress-debug-sections=zlib-gnu
--compress-debug-sections=zlib-gabi
--compress-debug-sections=zstd
Для ELF-файлов эти опции управляют тем, как сжимаются секции DWARF отладки. --compress-debug-sections=none эквивалентно --decompress-debug-sections. --compress-debug-sections=zlib и --compress-debug-sections=zlib-gabi эквивалентны --compress-debug-sections. --compress-debug-sections=zlib-gnu сжимает секции DWARF отладки с помощью устаревшего формата zlib-gnu. Секции отладки переименовываются, чтобы начинаться с .zdebug. --compress-debug-sections=zstd сжимает секции DWARF отладки с помощью zstd. Обратите внимание — если сжатие фактически сделает секцию больше, то она не сжимается и не переименовывается.
--decompress-debug-sections
Разжать секции DWARF отладки. Для секции .zdebug восстанавливается исходное имя.
--elf-stt-common=yes
--elf-stt-common=no
Для ELF-файлов эти опции управляют тем, должны ли общие символы быть преобразованы в тип "STT_COMMON" или "STT_OBJECT". --elf-stt-common=yes преобразует тип общего символа в "STT_COMMON". --elf-stt-common=no преобразует тип общего символа в "STT_OBJECT".
--merge-notes
--no-merge-notes
Для ELF-файлов попытаться (или не попытаться) уменьшить размер любых секций типа SHT_NOTE, удаляя дублирующиеся заметки.
-V
--version
Показать номер версии objcopy.
--verilog-data-width=bytes
Для вывода Verilog эта опция управляет количеством байтов, преобразованных для каждого элемента выходных данных. Целевой ввод управляет порядком байтов преобразования.
-v
--verbose
Подробный вывод: перечислить все изменённые объектные файлы. В случае архивов objcopy -V перечисляет все члены архива.
--help
Показать сводку опций для objcopy.
--info
Отобразить список, показывающий все доступные архитектуры и форматы объектных файлов.
@file
Читать опции командной строки из файла. Прочитанные опции вставляются на место оригинальной опции @file. Если файл не существует или не может быть прочитан, опция будет обработана буквально и не удалена.
Опции в файле разделены пробелами. Символ пробела можно включить в опцию, окружив всю опцию одиночными или двойными кавычками. Любые символы (включая обратную косую черту) можно включить, предваряя символ, который нужно включить, обратной косой чертой. Файл сам может содержать дополнительные опции @file; любые такие опции будут обработаны рекурсивно.
SEE ALSO
ld(1), objdump(1), и записи Info для binutils.
COPYRIGHT
Copyright (c) 1991-2025 Free Software Foundation, Inc.
Разрешается копировать, распространять и/или изменять этот документ на условиях Лицензии GNU Free Documentation License, версии 1.3 или любой более поздней версии, опубликованной Free Software Foundation; без Инвариантных Разделов, без Текстов Обложки и без Текстов Задней Обложки. Копия лицензии включена в раздел, озаглавленный "GNU Free Documentation License".
binutils-2.44 2025-05-12 OBJCOPY(1)
OBJCOPY(1) GNU Development Tools OBJCOPY(1)
NAME
objcopy - copy and translate object files
SYNOPSIS
objcopy [-F bfdname|--target=bfdname]
[-I bfdname|--input-target=bfdname]
[-O bfdname|--output-target=bfdname]
[-B bfdarch|--binary-architecture=bfdarch]
[-S|--strip-all]
[-g|--strip-debug]
[--strip-unneeded]
[-K symbolname|--keep-symbol=symbolname]
[--keep-file-symbols]
[--keep-section-symbols]
[-N symbolname|--strip-symbol=symbolname]
[--strip-unneeded-symbol=symbolname]
[-G symbolname|--keep-global-symbol=symbolname]
[--localize-hidden]
[-L symbolname|--localize-symbol=symbolname]
[--globalize-symbol=symbolname]
[--globalize-symbols=filename]
[-W symbolname|--weaken-symbol=symbolname]
[-w|--wildcard]
[-x|--discard-all]
[-X|--discard-locals]
[-b byte|--byte=byte]
[-i [breadth]|--interleave[=breadth]]
[--interleave-width=width]
[-j sectionpattern|--only-section=sectionpattern]
[-R sectionpattern|--remove-section=sectionpattern]
[--keep-section=sectionpattern]
[--remove-relocations=sectionpattern]
[--strip-section-headers]
[-p|--preserve-dates]
[-D|--enable-deterministic-archives]
[-U|--disable-deterministic-archives]
[--debugging]
[--gap-fill=val]
[--pad-to=address]
[--set-start=val]
[--adjust-start=incr]
[--change-addresses=incr]
[--change-section-address sectionpattern{=,+,-}val]
[--change-section-lma sectionpattern{=,+,-}val]
[--change-section-vma sectionpattern{=,+,-}val]
[--change-warnings] [--no-change-warnings]
[--set-section-flags sectionpattern=flags]
[--set-section-alignment sectionpattern=align]
[--add-section sectionname=filename]
[--dump-section sectionname=filename]
[--update-section sectionname=filename]
[--rename-section oldname=newname[,flags]]
[--long-section-names {enable,disable,keep}]
[--change-leading-char] [--remove-leading-char]
[--reverse-bytes=num]
[--srec-len=ival] [--srec-forceS3]
[--redefine-sym old=new]
[--redefine-syms=filename]
[--weaken]
[--keep-symbols=filename]
[--strip-symbols=filename]
[--strip-unneeded-symbols=filename]
[--keep-global-symbols=filename]
[--localize-symbols=filename]
[--weaken-symbols=filename]
[--add-symbol name=[section:]value[,flags]]
[--alt-machine-code=index]
[--prefix-symbols=string]
[--prefix-sections=string]
[--prefix-alloc-sections=string]
[--add-gnu-debuglink=path-to-file]
[--only-keep-debug]
[--strip-dwo]
[--extract-dwo]
[--extract-symbol]
[--writable-text]
[--readonly-text]
[--pure]
[--impure]
[--file-alignment=num]
[--heap=reserve[,commit]]
[--image-base=address]
[--section-alignment=num]
[--stack=reserve[,commit]]
[--subsystem=which:major.minor]
[--compress-debug-sections]
[--decompress-debug-sections]
[--elf-stt-common=val]
[--merge-notes]
[--no-merge-notes]
[--verilog-data-width=val]
[-v|--verbose]
[-V|--version]
[--help] [--info]
infile [outfile]
DESCRIPTION
The GNU objcopy utility copies the contents of an object file to
another. objcopy uses the GNU BFD Library to read and write the object
files. It can write the destination object file in a format different
from that of the source object file. The exact behavior of objcopy is
controlled by command-line options. Note that objcopy should be able
to copy a fully linked file between any two formats. However, copying a
relocatable object file between any two formats may not work as
expected.
objcopy creates temporary files to do its translations and deletes them
afterward. objcopy uses BFD to do all its translation work; it has
access to all the formats described in BFD and thus is able to
recognize most formats without being told explicitly.
objcopy can be used to generate S-records by using an output target of
srec (e.g., use -O srec).
objcopy can be used to generate a raw binary file by using an output
target of binary (e.g., use -O binary). When objcopy generates a raw
binary file, it will essentially produce a memory dump of the contents
of the input object file. All symbols and relocation information will
be discarded. The memory dump will start at the load address of the
lowest section copied into the output file.
When generating an S-record or a raw binary file, it may be helpful to
use -S to remove sections containing debugging information. In some
cases -R will be useful to remove sections which contain information
that is not needed by the binary file.
Note---objcopy is not able to change the endianness of its input files.
If the input format has an endianness (some formats do not), objcopy
can only copy the inputs into file formats that have the same
endianness or which have no endianness (e.g., srec). (However, see the
--reverse-bytes option.)
OPTIONS
infile
outfile
The input and output files, respectively. If you do not specify
outfile, objcopy creates a temporary file and destructively renames
the result with the name of infile.
-I bfdname
--input-target=bfdname
Consider the source file's object format to be bfdname, rather than
attempting to deduce it.
-O bfdname
--output-target=bfdname
Write the output file using the object format bfdname.
-F bfdname
--target=bfdname
Use bfdname as the object format for both the input and the output
file; i.e., simply transfer data from source to destination with no
translation.
-B bfdarch
--binary-architecture=bfdarch
Useful when transforming a architecture-less input file into an
object file. In this case the output architecture can be set to
bfdarch. This option will be ignored if the input file has a known
bfdarch. You can access this binary data inside a program by
referencing the special symbols that are created by the conversion
process. These symbols are called _binary_objfile_start,
_binary_objfile_end and _binary_objfile_size. e.g. you can
transform a picture file into an object file and then access it in
your code using these symbols.
-j sectionpattern
--only-section=sectionpattern
Copy only the indicated sections from the input file to the output
file. This option may be given more than once. Note that using
this option inappropriately may make the output file unusable.
Wildcard characters are accepted in sectionpattern.
If the first character of sectionpattern is the exclamation point
(!) then matching sections will not be copied, even if earlier use
of --only-section on the same command line would otherwise copy it.
For example:
--only-section=.text.* --only-section=!.text.foo
will copy all sectinos matching '.text.*' but not the section
'.text.foo'.
-R sectionpattern
--remove-section=sectionpattern
Remove any section matching sectionpattern from the output file.
This option may be given more than once. Note that using this
option inappropriately may make the output file unusable. Wildcard
characters are accepted in sectionpattern. Using both the -j and
-R options together results in undefined behaviour.
If the first character of sectionpattern is the exclamation point
(!) then matching sections will not be removed even if an earlier
use of --remove-section on the same command line would otherwise
remove it. For example:
--remove-section=.text.* --remove-section=!.text.foo
will remove all sections matching the pattern '.text.*', but will
not remove the section '.text.foo'.
--keep-section=sectionpattern
When removing sections from the output file, keep sections that
match sectionpattern.
--remove-relocations=sectionpattern
Remove non-dynamic relocations from the output file for any section
matching sectionpattern. This option may be given more than once.
Note that using this option inappropriately may make the output
file unusable, and attempting to remove a dynamic relocation
section such as .rela.plt from an executable or shared library with
--remove-relocations=.plt will not work. Wildcard characters are
accepted in sectionpattern. For example:
--remove-relocations=.text.*
will remove the relocations for all sections matching the pattern
'.text.*'.
If the first character of sectionpattern is the exclamation point
(!) then matching sections will not have their relocation removed
even if an earlier use of --remove-relocations on the same command
line would otherwise cause the relocations to be removed. For
example:
--remove-relocations=.text.* --remove-relocations=!.text.foo
will remove all relocations for sections matching the pattern
'.text.*', but will not remove relocations for the section
'.text.foo'.
--strip-section-headers
Strip section header This option is specific to ELF files.
Implies --strip-all and --merge-notes.
-S
--strip-all
Do not copy relocation and symbol information from the source file.
Also deletes debug sections.
-g
--strip-debug
Do not copy debugging symbols or sections from the source file.
--strip-unneeded
Remove all symbols that are not needed for relocation processing in
addition to debugging symbols and sections stripped by
--strip-debug.
-K symbolname
--keep-symbol=symbolname
When stripping symbols, keep symbol symbolname even if it would
normally be stripped. This option may be given more than once.
-N symbolname
--strip-symbol=symbolname
Do not copy symbol symbolname from the source file. This option
may be given more than once.
--strip-unneeded-symbol=symbolname
Do not copy symbol symbolname from the source file unless it is
needed by a relocation. This option may be given more than once.
-G symbolname
--keep-global-symbol=symbolname
Keep only symbol symbolname global. Make all other symbols local
to the file, so that they are not visible externally. This option
may be given more than once. Note: this option cannot be used in
conjunction with the --globalize-symbol or --globalize-symbols
options.
--localize-hidden
In an ELF object, mark all symbols that have hidden or internal
visibility as local. This option applies on top of symbol-specific
localization options such as -L.
-L symbolname
--localize-symbol=symbolname
Convert a global or weak symbol called symbolname into a local
symbol, so that it is not visible externally. This option may be
given more than once. Note - unique symbols are not converted.
-W symbolname
--weaken-symbol=symbolname
Make symbol symbolname weak. This option may be given more than
once.
--globalize-symbol=symbolname
Give symbol symbolname global scoping so that it is visible outside
of the file in which it is defined. This option may be given more
than once. Note: this option cannot be used in conjunction with
the -G or --keep-global-symbol options.
-w
--wildcard
Permit regular expressions in symbolnames used in other command
line options. The question mark (?), asterisk (*), backslash (\)
and square brackets ([]) operators can be used anywhere in the
symbol name. If the first character of the symbol name is the
exclamation point (!) then the sense of the switch is reversed for
that symbol. For example:
-w -W !foo -W fo*
would cause objcopy to weaken all symbols that start with "fo"
except for the symbol "foo".
-x
--discard-all
Do not copy non-global symbols from the source file.
-X
--discard-locals
Do not copy compiler-generated local symbols. (These usually start
with L or ..)
-b byte
--byte=byte
If interleaving has been enabled via the --interleave option then
start the range of bytes to keep at the byteth byte. byte can be
in the range from 0 to breadth-1, where breadth is the value given
by the --interleave option.
-i [breadth]
--interleave[=breadth]
Only copy a range out of every breadth bytes. (Header data is not
affected). Select which byte in the range begins the copy with the
--byte option. Select the width of the range with the
--interleave-width option.
This option is useful for creating files to program ROM. It is
typically used with an "srec" output target. Note that objcopy
will complain if you do not specify the --byte option as well.
The default interleave breadth is 4, so with --byte set to 0,
objcopy would copy the first byte out of every four bytes from the
input to the output.
--interleave-width=width
When used with the --interleave option, copy width bytes at a time.
The start of the range of bytes to be copied is set by the --byte
option, and the extent of the range is set with the --interleave
option.
The default value for this option is 1. The value of width plus
the byte value set by the --byte option must not exceed the
interleave breadth set by the --interleave option.
This option can be used to create images for two 16-bit flashes
interleaved in a 32-bit bus by passing -b 0 -i 4
--interleave-width=2 and -b 2 -i 4 --interleave-width=2 to two
objcopy commands. If the input was '12345678' then the outputs
would be '1256' and '3478' respectively.
-p
--preserve-dates
Set the access and modification dates of the output file to be the
same as those of the input file.
This option also copies the date stored in a PE format file's
header, unless the SOURCE_DATE_EPOCH environment variable is
defined. If it is defined then this variable will be used as the
date stored in the header, interpreted as the number of seconds
since the Unix epoch.
-D
--enable-deterministic-archives
Operate in deterministic mode. When copying archive members and
writing the archive index, use zero for UIDs, GIDs, timestamps, and
use consistent file modes for all files.
If binutils was configured with --enable-deterministic-archives,
then this mode is on by default. It can be disabled with the -U
option, below.
-U
--disable-deterministic-archives
Do not operate in deterministic mode. This is the inverse of the
-D option, above: when copying archive members and writing the
archive index, use their actual UID, GID, timestamp, and file mode
values.
This is the default unless binutils was configured with
--enable-deterministic-archives.
--debugging
Convert debugging information, if possible. This is not the
default because only certain debugging formats are supported, and
the conversion process can be time consuming.
--gap-fill val
Fill gaps between sections with val. This operation applies to the
load address (LMA) of the sections. It is done by increasing the
size of the section with the lower address, and filling in the
extra space created with val.
--pad-to address
Pad the output file up to the load address address. This is done
by increasing the size of the last section. The extra space is
filled in with the value specified by --gap-fill (default zero).
--set-start val
Set the start address (also known as the entry address) of the new
file to val. Not all object file formats support setting the start
address.
--change-start incr
--adjust-start incr
Change the start address (also known as the entry address) by
adding incr. Not all object file formats support setting the start
address.
--change-addresses incr
--adjust-vma incr
Change the VMA and LMA addresses of all sections, as well as the
start address, by adding incr. Some object file formats do not
permit section addresses to be changed arbitrarily. Note that this
does not relocate the sections; if the program expects sections to
be loaded at a certain address, and this option is used to change
the sections such that they are loaded at a different address, the
program may fail.
--change-section-address sectionpattern{=,+,-}val
--adjust-section-vma sectionpattern{=,+,-}val
Set or change both the VMA address and the LMA address of any
section matching sectionpattern. If = is used, the section address
is set to val. Otherwise, val is added to or subtracted from the
section address. See the comments under --change-addresses, above.
If sectionpattern does not match any sections in the input file, a
warning will be issued, unless --no-change-warnings is used.
--change-section-lma sectionpattern{=,+,-}val
Set or change the LMA address of any sections matching
sectionpattern. The LMA address is the address where the section
will be loaded into memory at program load time. Normally this is
the same as the VMA address, which is the address of the section at
program run time, but on some systems, especially those where a
program is held in ROM, the two can be different. If = is used,
the section address is set to val. Otherwise, val is added to or
subtracted from the section address. See the comments under
--change-addresses, above. If sectionpattern does not match any
sections in the input file, a warning will be issued, unless
--no-change-warnings is used.
--change-section-vma sectionpattern{=,+,-}val
Set or change the VMA address of any section matching
sectionpattern. The VMA address is the address where the section
will be located once the program has started executing. Normally
this is the same as the LMA address, which is the address where the
section will be loaded into memory, but on some systems, especially
those where a program is held in ROM, the two can be different. If
= is used, the section address is set to val. Otherwise, val is
added to or subtracted from the section address. See the comments
under --change-addresses, above. If sectionpattern does not match
any sections in the input file, a warning will be issued, unless
--no-change-warnings is used.
Note - changing the VMA of sections in a fully linked binary can be
dangerous since there may be code that expects the sections to be
located at their old address.
--change-warnings
--adjust-warnings
If --change-section-address or --change-section-lma or
--change-section-vma is used, and the section pattern does not
match any sections, issue a warning. This is the default.
--no-change-warnings
--no-adjust-warnings
Do not issue a warning if --change-section-address or
--adjust-section-lma or --adjust-section-vma is used, even if the
section pattern does not match any sections.
--set-section-flags sectionpattern=flags
Set the flags for any sections matching sectionpattern. The flags
argument is a comma separated string of flag names. The recognized
names are alloc, contents, load, noload, readonly, code, data, rom,
exclude, share, debug, and large. You can set the contents flag
for a section which does not have contents, but it is not
meaningful to clear the contents flag of a section which does have
contents--just remove the section instead. Not all flags are
meaningful for all object file formats. In particular the share
flag is only meaningful for COFF format files and not for ELF
format files. The ELF x86-64 specific flag large corresponds to
SHF_X86_64_LARGE.
--set-section-alignment sectionpattern=align
Set the alignment for any sections matching sectionpattern. align
specifies the alignment in bytes and must be a power of two, i.e.
1, 2, 4, 8....
Note - setting a section's alignment will not automatically align
its LMA or VMA addresses. If those need to be changed as well then
the --change-section-lma and/or --change-section-vma options should
be used. Also note that changing VMAs can cause problems in fully
linked binaries where there may be code that expects the contents
of the sections to be located at their old address.
--add-section sectionname=filename
Add a new section named sectionname while copying the file. The
contents of the new section are taken from the file filename. The
size of the section will be the size of the file. This option only
works on file formats which can support sections with arbitrary
names. Note - it may be necessary to use the --set-section-flags
option to set the attributes of the newly created section.
--dump-section sectionname=filename
Place the contents of section named sectionname into the file
filename, overwriting any contents that may have been there
previously. This option is the inverse of --add-section. This
option is similar to the --only-section option except that it does
not create a formatted file, it just dumps the contents as raw
binary data, without applying any relocations. The option can be
specified more than once.
--update-section sectionname=filename
Replace the existing contents of a section named sectionname with
the contents of file filename. The size of the section will be
adjusted to the size of the file. The section flags for
sectionname will be unchanged. For ELF format files the section to
segment mapping will also remain unchanged, something which is not
possible using --remove-section followed by --add-section. The
option can be specified more than once.
Note - it is possible to use --rename-section and --update-section
to both update and rename a section from one command line. In this
case, pass the original section name to --update-section, and the
original and new section names to --rename-section.
--add-symbol name=[section:]value[,flags]
Add a new symbol named name while copying the file. This option
may be specified multiple times. If the section is given, the
symbol will be associated with and relative to that section,
otherwise it will be an ABS symbol. Specifying an undefined
section will result in a fatal error. There is no check for the
value, it will be taken as specified. Symbol flags can be
specified and not all flags will be meaningful for all object file
formats. By default, the symbol will be global. The special flag
'before=othersym' will insert the new symbol in front of the
specified othersym, otherwise the symbol(s) will be added at the
end of the symbol table in the order they appear.
--rename-section oldname=newname[,flags]
Rename a section from oldname to newname, optionally changing the
section's flags to flags in the process. This has the advantage
over using a linker script to perform the rename in that the output
stays as an object file and does not become a linked executable.
This option accepts the same set of flags as the
--set-section-flags option.
This option is particularly helpful when the input format is
binary, since this will always create a section called .data. If
for example, you wanted instead to create a section called .rodata
containing binary data you could use the following command line to
achieve it:
objcopy -I binary -O <output_format> -B <architecture> \
--rename-section .data=.rodata,alloc,load,readonly,data,contents \
<input_binary_file> <output_object_file>
--long-section-names {enable,disable,keep}
Controls the handling of long section names when processing "COFF"
and "PE-COFF" object formats. The default behaviour, keep, is to
preserve long section names if any are present in the input file.
The enable and disable options forcibly enable or disable the use
of long section names in the output object; when disable is in
effect, any long section names in the input object will be
truncated. The enable option will only emit long section names if
any are present in the inputs; this is mostly the same as keep, but
it is left undefined whether the enable option might force the
creation of an empty string table in the output file.
--change-leading-char
Some object file formats use special characters at the start of
symbols. The most common such character is underscore, which
compilers often add before every symbol. This option tells objcopy
to change the leading character of every symbol when it converts
between object file formats. If the object file formats use the
same leading character, this option has no effect. Otherwise, it
will add a character, or remove a character, or change a character,
as appropriate.
--remove-leading-char
If the first character of a global symbol is a special symbol
leading character used by the object file format, remove the
character. The most common symbol leading character is underscore.
This option will remove a leading underscore from all global
symbols. This can be useful if you want to link together objects
of different file formats with different conventions for symbol
names. This is different from --change-leading-char because it
always changes the symbol name when appropriate, regardless of the
object file format of the output file.
--reverse-bytes=num
Reverse the bytes in a section with output contents. A section
length must be evenly divisible by the value given in order for the
swap to be able to take place. Reversing takes place before the
interleaving is performed.
This option is used typically in generating ROM images for
problematic target systems. For example, on some target boards,
the 32-bit words fetched from 8-bit ROMs are re-assembled in
little-endian byte order regardless of the CPU byte order.
Depending on the programming model, the endianness of the ROM may
need to be modified.
Consider a simple file with a section containing the following
eight bytes: 12345678.
Using --reverse-bytes=2 for the above example, the bytes in the
output file would be ordered 21436587.
Using --reverse-bytes=4 for the above example, the bytes in the
output file would be ordered 43218765.
By using --reverse-bytes=2 for the above example, followed by
--reverse-bytes=4 on the output file, the bytes in the second
output file would be ordered 34127856.
--srec-len=ival
Meaningful only for srec output. Set the maximum length of the
Srecords being produced to ival. This length covers both address,
data and crc fields.
--srec-forceS3
Meaningful only for srec output. Avoid generation of S1/S2
records, creating S3-only record format.
--redefine-sym old=new
Change the name of a symbol old, to new. This can be useful when
one is trying link two things together for which you have no
source, and there are name collisions.
--redefine-syms=filename
Apply --redefine-sym to each symbol pair "old new" listed in the
file filename. filename is simply a flat file, with one symbol
pair per line. Line comments may be introduced by the hash
character. This option may be given more than once.
--weaken
Change all global symbols in the file to be weak. This can be
useful when building an object which will be linked against other
objects using the -R option to the linker. This option is only
effective when using an object file format which supports weak
symbols.
--keep-symbols=filename
Apply --keep-symbol option to each symbol listed in the file
filename. filename is simply a flat file, with one symbol name per
line. Line comments may be introduced by the hash character. This
option may be given more than once.
--strip-symbols=filename
Apply --strip-symbol option to each symbol listed in the file
filename. filename is simply a flat file, with one symbol name per
line. Line comments may be introduced by the hash character. This
option may be given more than once.
--strip-unneeded-symbols=filename
Apply --strip-unneeded-symbol option to each symbol listed in the
file filename. filename is simply a flat file, with one symbol
name per line. Line comments may be introduced by the hash
character. This option may be given more than once.
--keep-global-symbols=filename
Apply --keep-global-symbol option to each symbol listed in the file
filename. filename is simply a flat file, with one symbol name per
line. Line comments may be introduced by the hash character. This
option may be given more than once.
--localize-symbols=filename
Apply --localize-symbol option to each symbol listed in the file
filename. filename is simply a flat file, with one symbol name per
line. Line comments may be introduced by the hash character. This
option may be given more than once.
--globalize-symbols=filename
Apply --globalize-symbol option to each symbol listed in the file
filename. filename is simply a flat file, with one symbol name per
line. Line comments may be introduced by the hash character. This
option may be given more than once. Note: this option cannot be
used in conjunction with the -G or --keep-global-symbol options.
--weaken-symbols=filename
Apply --weaken-symbol option to each symbol listed in the file
filename. filename is simply a flat file, with one symbol name per
line. Line comments may be introduced by the hash character. This
option may be given more than once.
--alt-machine-code=index
If the output architecture has alternate machine codes, use the
indexth code instead of the default one. This is useful in case a
machine is assigned an official code and the tool-chain adopts the
new code, but other applications still depend on the original code
being used. For ELF based architectures if the index alternative
does not exist then the value is treated as an absolute number to
be stored in the e_machine field of the ELF header.
--writable-text
Mark the output text as writable. This option isn't meaningful for
all object file formats.
--readonly-text
Make the output text write protected. This option isn't meaningful
for all object file formats.
--pure
Mark the output file as demand paged. This option isn't meaningful
for all object file formats.
--impure
Mark the output file as impure. This option isn't meaningful for
all object file formats.
--prefix-symbols=string
Prefix all symbols in the output file with string.
--prefix-sections=string
Prefix all section names in the output file with string.
--prefix-alloc-sections=string
Prefix all the names of all allocated sections in the output file
with string.
--add-gnu-debuglink=path-to-file
Creates a .gnu_debuglink section which contains a reference to
path-to-file and adds it to the output file. Note: the file at
path-to-file must exist. Part of the process of adding the
.gnu_debuglink section involves embedding a checksum of the
contents of the debug info file into the section.
If the debug info file is built in one location but it is going to
be installed at a later time into a different location then do not
use the path to the installed location. The --add-gnu-debuglink
option will fail because the installed file does not exist yet.
Instead put the debug info file in the current directory and use
the --add-gnu-debuglink option without any directory components,
like this:
objcopy --add-gnu-debuglink=foo.debug
At debug time the debugger will attempt to look for the separate
debug info file in a set of known locations. The exact set of
these locations varies depending upon the distribution being used,
but it typically includes:
"* The same directory as the executable."
"* A sub-directory of the directory containing the executable"
called .debug
"* A global debug directory such as /usr/lib/debug."
As long as the debug info file has been installed into one of these
locations before the debugger is run everything should work
correctly.
--keep-section-symbols
When stripping a file, perhaps with --strip-debug or
--strip-unneeded, retain any symbols specifying section names,
which would otherwise get stripped.
--keep-file-symbols
When stripping a file, perhaps with --strip-debug or
--strip-unneeded, retain any symbols specifying source file names,
which would otherwise get stripped.
--only-keep-debug
Strip a file, removing contents of any sections that would not be
stripped by --strip-debug and leaving the debugging sections
intact. In ELF files, this preserves all note sections in the
output.
Note - the section headers of the stripped sections are preserved,
including their sizes, but the contents of the section are
discarded. The section headers are preserved so that other tools
can match up the debuginfo file with the real executable, even if
that executable has been relocated to a different address space.
The intention is that this option will be used in conjunction with
--add-gnu-debuglink to create a two part executable. One a
stripped binary which will occupy less space in RAM and in a
distribution and the second a debugging information file which is
only needed if debugging abilities are required. The suggested
procedure to create these files is as follows:
1.<Link the executable as normal. Assuming that it is called>
"foo" then...
1.<Run "objcopy --only-keep-debug foo foo.dbg" to>
create a file containing the debugging info.
1.<Run "objcopy --strip-debug foo" to create a>
stripped executable.
1.<Run "objcopy --add-gnu-debuglink=foo.dbg foo">
to add a link to the debugging info into the stripped
executable.
Note---the choice of ".dbg" as an extension for the debug info file
is arbitrary. Also the "--only-keep-debug" step is optional. You
could instead do this:
1.<Link the executable as normal.>
1.<Copy "foo" to "foo.full">
1.<Run "objcopy --strip-debug foo">
1.<Run "objcopy --add-gnu-debuglink=foo.full foo">
i.e., the file pointed to by the --add-gnu-debuglink can be the
full executable. It does not have to be a file created by the
--only-keep-debug switch.
Note---this switch is only intended for use on fully linked files.
It does not make sense to use it on object files where the
debugging information may be incomplete. Besides the gnu_debuglink
feature currently only supports the presence of one filename
containing debugging information, not multiple filenames on a one-
per-object-file basis.
--strip-dwo
Remove the contents of all DWARF .dwo sections, leaving the
remaining debugging sections and all symbols intact. This option
is intended for use by the compiler as part of the -gsplit-dwarf
option, which splits debug information between the .o file and a
separate .dwo file. The compiler generates all debug information
in the same file, then uses the --extract-dwo option to copy the
.dwo sections to the .dwo file, then the --strip-dwo option to
remove those sections from the original .o file.
--extract-dwo
Extract the contents of all DWARF .dwo sections. See the
--strip-dwo option for more information.
--file-alignment num
Specify the file alignment. Sections in the file will always begin
at file offsets which are multiples of this number. This defaults
to 512. [This option is specific to PE targets.]
--heap reserve
--heap reserve,commit
Specify the number of bytes of memory to reserve (and optionally
commit) to be used as heap for this program. [This option is
specific to PE targets.]
--image-base value
Use value as the base address of your program or dll. This is the
lowest memory location that will be used when your program or dll
is loaded. To reduce the need to relocate and improve performance
of your dlls, each should have a unique base address and not
overlap any other dlls. The default is 0x400000 for executables,
and 0x10000000 for dlls. [This option is specific to PE targets.]
--section-alignment num
[This option is specific to PE targets.]
Sets the section alignment field in the PE header - if one is
present in the binary. Sections in memory will always begin at
addresses which are a multiple of this number. Defaults to 0x1000.
Note - this option will also set the alignment field in each
section's flags.
Note - if a section's LMA or VMA addresses are no longer aligned,
and those addresses have not been set via the --set-section-lma or
--set-section-vma options, and the file has been fully relocated
then a warning message will be issued. It will then be up to the
user to decide if the LMA and VMA need updating.
--stack reserve
--stack reserve,commit
Specify the number of bytes of memory to reserve (and optionally
commit) to be used as stack for this program. [This option is
specific to PE targets.]
--subsystem which
--subsystem which:major
--subsystem which:major.minor
Specifies the subsystem under which your program will execute. The
legal values for which are "native", "windows", "console", "posix",
"efi-app", "efi-bsd", "efi-rtd", "sal-rtd", and "xbox". You may
optionally set the subsystem version also. Numeric values are also
accepted for which. [This option is specific to PE targets.]
--extract-symbol
Keep the file's section flags and symbols but remove all section
data. Specifically, the option:
*<removes the contents of all sections;>
*<sets the size of every section to zero; and>
*<sets the file's start address to zero.>
This option is used to build a .sym file for a VxWorks kernel. It
can also be a useful way of reducing the size of a --just-symbols
linker input file.
--compress-debug-sections
Compress DWARF debug sections using zlib with SHF_COMPRESSED from
the ELF ABI. Note - if compression would actually make a section
larger, then it is not compressed.
--compress-debug-sections=none
--compress-debug-sections=zlib
--compress-debug-sections=zlib-gnu
--compress-debug-sections=zlib-gabi
--compress-debug-sections=zstd
For ELF files, these options control how DWARF debug sections are
compressed. --compress-debug-sections=none is equivalent to
--decompress-debug-sections. --compress-debug-sections=zlib and
--compress-debug-sections=zlib-gabi are equivalent to
--compress-debug-sections. --compress-debug-sections=zlib-gnu
compresses DWARF debug sections using the obsoleted zlib-gnu
format. The debug sections are renamed to begin with .zdebug.
--compress-debug-sections=zstd compresses DWARF debug sections
using zstd. Note - if compression would actually make a section
larger, then it is not compressed nor renamed.
--decompress-debug-sections
Decompress DWARF debug sections. For a .zdebug section, the
original name is restored.
--elf-stt-common=yes
--elf-stt-common=no
For ELF files, these options control whether common symbols should
be converted to the "STT_COMMON" or "STT_OBJECT" type.
--elf-stt-common=yes converts common symbol type to "STT_COMMON".
--elf-stt-common=no converts common symbol type to "STT_OBJECT".
--merge-notes
--no-merge-notes
For ELF files, attempt (or do not attempt) to reduce the size of
any SHT_NOTE type sections by removing duplicate notes.
-V
--version
Show the version number of objcopy.
--verilog-data-width=bytes
For Verilog output, this options controls the number of bytes
converted for each output data element. The input target controls
the endianness of the conversion.
-v
--verbose
Verbose output: list all object files modified. In the case of
archives, objcopy -V lists all members of the archive.
--help
Show a summary of the options to objcopy.
--info
Display a list showing all architectures and object formats
available.
@file
Read command-line options from file. The options read are inserted
in place of the original @file option. If file does not exist, or
cannot be read, then the option will be treated literally, and not
removed.
Options in file are separated by whitespace. A whitespace
character may be included in an option by surrounding the entire
option in either single or double quotes. Any character (including
a backslash) may be included by prefixing the character to be
included with a backslash. The file may itself contain additional
@file options; any such options will be processed recursively.
SEE ALSO
ld(1), objdump(1), and the Info entries for binutils.
COPYRIGHT
Copyright (c) 1991-2025 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3 or
any later version published by the Free Software Foundation; with no
Invariant Sections, with no Front-Cover Texts, and with no Back-Cover
Texts. A copy of the license is included in the section entitled "GNU
Free Documentation License".
binutils-2.44 2025-05-12 OBJCOPY(1)
NM(1) GNU Development Tools NM(1)
NAME
nm - вывести список символов из объектных файлов
SYNOPSIS
nm [-A|-o|--print-file-name]
[-a|--debug-syms]
[-B|--format=bsd]
[-C|--demangle[=style]]
[-D|--dynamic]
[-fformat|--format=format]
[-g|--extern-only]
[-h|--help]
[--ifunc-chars=CHARS]
[-j|--format=just-symbols]
[-l|--line-numbers] [--inlines]
[-n|-v|--numeric-sort]
[-P|--portability]
[-p|--no-sort]
[-r|--reverse-sort]
[-S|--print-size]
[-s|--print-armap]
[-t radix|--radix=radix]
[-u|--undefined-only]
[-U|--defined-only]
[-V|--version]
[-W|--no-weak]
[-X 32_64]
[--no-demangle]
[--no-recurse-limit|--recurse-limit]
[--plugin name]
[--size-sort]
[--special-syms]
[--synthetic]
[--target=bfdname]
[--unicode=method]
[--with-symbol-versions]
[--without-symbol-versions]
[objfile...]
DESCRIPTION
GNU nm выводит список символов из объектных файлов objfile.... Если объектные файлы не указаны в аргументах, nm предполагает файл a.out.
Для каждого символа nm показывает:
• Значение символа в системе счисления, выбранной опциями (см. ниже), или в шестнадцатеричной системе по умолчанию.
• Тип символа. Используются как минимум следующие типы; другие также могут использоваться в зависимости от формата объектного файла. Если тип в нижнем регистре, символ обычно локальный; если в верхнем регистре, символ глобальный (внешний). Однако есть несколько символов в нижнем регистре, которые отображаются для специальных глобальных символов ("u", "v" и "w").
"A" Значение символа абсолютное и не будет изменено при дальнейшей связывании.
"B"
"b" Символ находится в секции BSS данных. Эта секция обычно содержит данные, инициализированные нулями или неинициализированные, хотя точное поведение зависит от системы.
"C"
"c" Символ является общим. Общие символы представляют неинициализированные данные. При связывании несколько общих символов с одинаковым именем могут появиться. Если символ определён где-либо, общие символы рассматриваются как неопределённые ссылки. Символ в нижнем регистре "c" используется, когда символ находится в специальной секции для малых общих символов.
"D"
"d" Символ находится в секции инициализированных данных.
"G"
"g" Символ находится в секции инициализированных данных для малых объектов. Некоторые форматы объектных файлов позволяют более эффективный доступ к малым объектам данных, таким как глобальная переменная int по сравнению с большим глобальным массивом.
"i" Для файлов в формате PE это указывает, что символ находится в секции, специфичной для реализации DLL.
Для файлов в формате ELF это указывает, что символ является косвенной функцией. Это расширение GNU для стандартного набора типов символов ELF. Оно обозначает символ, который, если на него ссылается релокация, не оценивается по своему адресу, а вместо этого должен быть вызван во время выполнения. Выполнение во время выполнения затем вернёт значение, которое будет использоваться в релокации.
Примечание: фактическое отображение символов GNU косвенных функций управляется опцией командной строки --ifunc-chars. Если эта опция предоставлена, первый символ в строке будет использоваться для глобальных косвенных символов функций. Если строка содержит второй символ, он будет использоваться для локальных косвенных символов функций.
"I" Символ является косвенной ссылкой на другой символ.
"N" Символ является символом отладки.
"n" Символ находится в секции, которая не является секцией данных, кода или отладки, и доступна только для чтения.
"p" Символ находится в секции размотки стека.
"R"
"r" Символ находится в секции данных только для чтения.
"S"
"s" Символ находится в секции неинициализированных или инициализированных нулями данных для малых объектов.
"T"
"t" Символ находится в секции текста (кода).
"U" Символ неопределённый.
"u" Символ является уникальным глобальным символом. Это расширение GNU для стандартного набора связей символов ELF. Для такого символа динамический линкер обеспечит, чтобы в целом процессе был использован только один символ с этим именем и типом.
"V"
"v" Символ является слабым объектом. Когда слабый определённый символ связывается с нормальным определённым символом, используется нормальный определённый символ без ошибок. Когда слабый неопределённый символ связывается и символ не определён, значение слабого символа становится нулевым без ошибок. На некоторых системах верхний регистр указывает, что указано значение по умолчанию.
"W"
"w" Символ является слабым символом, который не был специально помечен как слабый объектный символ. Когда слабый определённый символ связывается с нормальным определённым символом, используется нормальный определённый символ без ошибок. Когда слабый неопределённый символ связывается и символ не определён, значение символа определяется в зависимости от системы без ошибок. На некоторых системах верхний регистр указывает, что указано значение по умолчанию.
"-" Символ является символом stabs в объектном файле a.out. В этом случае следующие выводимые значения — это поле stabs other, поле stabs desc и тип stab. Символы stabs используются для хранения информации отладки.
"?" Тип символа неизвестен или специфичен для формата объектного файла.
• Имя символа. Если символ имеет связанную с ним информацию о версии, то информация о версии также отображается. Если версионированный символ неопределённый или скрытый от линкера, строка версии отображается как суффикс к имени символа, предшествуемый символом @. Например, foo@VER_1. Если версия является версией по умолчанию, которая используется при разрешении неверсионированных ссылок на символ, то она отображается как суффикс, предшествуемый двумя символами @. Например, foo@@VER_2.
OPTIONS
Длинные и короткие формы опций, показанные здесь как альтернативы, эквивалентны.
-A
-o
--print-file-name
Предшествовать каждому символу именем входного файла (или члена архива), в котором он был найден, вместо того, чтобы указывать входной файл один раз перед всеми его символами.
-a
--debug-syms
Отображать все символы, включая символы только для отладчика; обычно они не перечисляются.
-B То же, что и --format=bsd (для совместимости с nm MIPS).
-C
--demangle[=style]
Декодировать (разманглировать) низкоуровневые имена символов в пользовательские имена. Кроме удаления начального подчёркивания, добавленного системой, это делает читаемыми имена функций C++. Разные компиляторы имеют разные стили манглинга. Опциональный аргумент стиля разманглинга можно использовать для выбора подходящего стиля разманглинга для вашего компилятора.
--no-demangle
Не разманглировать низкоуровневые имена символов. Это значение по умолчанию.
--recurse-limit
--no-recurse-limit
--recursion-limit
--no-recursion-limit
Включить или отключить ограничение на количество рекурсии при разманглировании строк. Поскольку форматы именования позволяют бесконечный уровень рекурсии, возможно создать строки, декодирование которых истощит пространство стека на хост-машине, вызвав ошибку памяти. Ограничение пытается предотвратить это, ограничивая рекурсию 2048 уровнями вложенности.
По умолчанию это ограничение включено, но отключение может быть необходимым для разманглирования действительно сложных имён. Обратите внимание, однако, что если ограничение рекурсии отключено, возможно истощение стека, и любые отчёты об ошибках такого события будут отклонены.
-D
--dynamic
Отображать динамические символы вместо нормальных символов. Это имеет смысл только для динамических объектов, таких как определённые типы разделяемых библиотек.
-f format
--format=format
Использовать формат вывода format, который может быть "bsd", "sysv", "posix" или "just-symbols". По умолчанию "bsd". Только первый символ format значим; он может быть как в верхнем, так и в нижнем регистре.
-g
--extern-only
Отображать только внешние символы.
-h
--help
Показать сводку опций nm и выйти.
--ifunc-chars=CHARS
При отображении символов GNU косвенных функций nm по умолчанию использует символ "i" как для локальных, так и для глобальных косвенных функций. Опция --ifunc-chars позволяет пользователю указать строку, содержащую один или два символа. Первый символ будет использоваться для глобальных косвенных символов функций, а второй, если он присутствует, — для локальных косвенных символов функций.
j То же, что и --format=just-symbols.
-l
--line-numbers
Для каждого символа использовать информацию отладки для поиска имени файла и номера строки. Для определённого символа искать номер строки адреса символа. Для неопределённого символа искать номер строки записи релокации, которая ссылается на символ. Если информация о номере строки найдена, вывести её после другой информации о символе.
--inlines
Когда опция -l активна, если адрес принадлежит функции, которая была встроенной, эта опция заставляет вывести информацию источника для всех включающих областей до первой невыстроенной функции. Например, если "main" встроена "callee1", которая встроена "callee2", и адрес из "callee2", то информация источника для "callee1" и "main" также будет выведена.
-n
-v
--numeric-sort
Сортировать символы численно по их адресам, а не алфавитно по их именам.
-p
--no-sort
Не сортировать символы в каком-либо порядке; выводить их в порядке обнаружения.
-P
--portability
Использовать стандартный формат вывода POSIX.2 вместо формата по умолчанию. Эквивалентно -f posix.
-r
--reverse-sort
Обратить порядок сортировки (независимо от того, численная или алфавитная); пусть последние идут первыми.
-S
--print-size
Выводить как значение, так и размер определённых символов для стиля вывода "bsd". Эта опция не имеет эффекта для форматов объектных файлов, которые не записывают размеры символов, если не используется --size-sort, в этом случае отображается рассчитанный размер.
-s
--print-armap
При выводе символов из членов архива включать индекс: отображение (хранящееся в архиве ar или ranlib), указывающее, какие модули содержат определения для каких имён.
-t radix
--radix=radix
Использовать radix в качестве системы счисления для вывода значений символов. Она должна быть d для десятичной, o для восьмеричной или x для шестнадцатеричной.
-u
--undefined-only
Выводить только неопределённые символы (те, которые внешние для каждого объектного файла). По умолчанию выводятся как определённые, так и неопределённые символы.
-U
--defined-only
Выводить только определённые символы для каждого объектного файла. По умолчанию выводятся как определённые, так и неопределённые символы.
-V
--version
Показать номер версии nm и выйти.
-X Эта опция игнорируется для совместимости с версией nm AIX. Она принимает один параметр, который должен быть строкой 32_64. Режим по умолчанию для nm AIX соответствует -X 32, который не поддерживается GNU nm.
--plugin name
Загрузить плагин с именем name для добавления поддержки дополнительных типов целей. Эта опция доступна только если инструментарий был построен с включённой поддержкой плагинов.
Если --plugin не предоставлен, но поддержка плагинов включена, то nm перебирает файлы в ${libdir}/bfd-plugins в алфавитном порядке, и первый плагин, который заявляет о объекте, используется.
Пожалуйста, обратите внимание, что этот каталог поиска плагинов не тот, который используется опцией ld -plugin. Чтобы заставить nm использовать плагин линкера, его нужно скопировать в каталог ${libdir}/bfd-plugins. Для компиляций на основе GCC плагин линкера называется liblto_plugin.so.0.0.0. Для компиляций на основе Clang он называется LLVMgold.so. Плагин GCC всегда обратно совместим с более ранними версиями, так что достаточно скопировать последнюю.
--size-sort
Сортировать символы по размеру. Для объектов ELF размеры символов читаются из ELF; для других типов объектов размеры символов вычисляются как разница между значением символа и значением символа с следующим большим значением. Если используется формат вывода "bsd", размер символа выводится вместо значения, и для вывода обоих размера и значения нужно использовать -S.
Примечание: эта опция не работает, если включена --undefined-only, так как неопределённые символы не имеют размера.
--special-syms
Выводить символы, которые имеют специальное значение, специфичное для цели. Эти символы обычно используются целью для какой-то специальной обработки и обычно не полезны, если включены в нормальные списки символов. Например, для целей ARM эта опция пропустит символы отображения, используемые для обозначения переходов между кодом ARM, кодом THUMB и данными.
--synthetic
Включить синтетические символы в вывод. Это специальные символы, созданные линкером для различных целей. По умолчанию они не показываются, поскольку не являются частью исходного кода двоичного файла.
--unicode=[default|invalid|locale|escape|hex|highlight]
Управляет отображением многобайтовых символов, закодированных в UTF-8, в строках. Значение по умолчанию (--unicode=default) — не давать им специального лечения. Опция --unicode=locale отображает последовательность в текущей локали, которая может или не может их поддерживать. Опции --unicode=hex и --unicode=invalid отображаются как последовательности шестнадцатеричных байтов, заключённые в угловые скобки или фигурные скобки.
Опция --unicode=escape отображает их как escape-последовательности (\uxxxx), а опция --unicode=highlight — как escape-последовательности, выделенные красным (если устройство вывода это поддерживает). Цветовое выделение предназначено для привлечения внимания к наличию последовательностей unicode, где они могут быть не ожидаемы.
-W
--no-weak
Не отображать слабые символы.
--with-symbol-versions
--without-symbol-versions
Включить или отключить отображение информации о версии символа. Строка версии отображается как суффикс к имени символа, предшествуемый символом @. Например, foo@VER_1. Если версия является версией по умолчанию, которая используется при разрешении неверсионированных ссылок на символ, то она отображается как суффикс, предшествуемый двумя символами @. Например, foo@@VER_2. По умолчанию информация о версии символа отображается.
--target=bfdname
Указать формат кода объекта, отличный от формата по умолчанию вашей системы.
@file
Читать опции командной строки из файла. Прочитанные опции вставляются на место оригинальной опции @file. Если файл не существует или не может быть прочитан, опция будет рассматриваться буквально и не удалена.
Опции в файле разделены пробелами. Пробельный символ можно включить в опцию, окружив всю опцию одиночными или двойными кавычками. Любые символы (включая обратный слэш) можно включить, предваряя символ, который нужно включить, обратным слэшем. Файл может сам содержать дополнительные опции @file; такие опции будут обработаны рекурсивно.
SEE ALSO
ar(1), objdump(1), ranlib(1), и записи Info для binutils.
COPYRIGHT
Copyright (c) 1991-2025 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3 or
any later version published by the Free Software Foundation; with no
Invariant Sections, with no Front-Cover Texts, and with no Back-Cover
Texts. A copy of the license is included in the section entitled "GNU
Free Documentation License".
binutils-2.44 2025-05-12 NM(1)
NM(1) GNU Development Tools NM(1)
NAME
nm - list symbols from object files
SYNOPSIS
nm [-A|-o|--print-file-name]
[-a|--debug-syms]
[-B|--format=bsd]
[-C|--demangle[=style]]
[-D|--dynamic]
[-fformat|--format=format]
[-g|--extern-only]
[-h|--help]
[--ifunc-chars=CHARS]
[-j|--format=just-symbols]
[-l|--line-numbers] [--inlines]
[-n|-v|--numeric-sort]
[-P|--portability]
[-p|--no-sort]
[-r|--reverse-sort]
[-S|--print-size]
[-s|--print-armap]
[-t radix|--radix=radix]
[-u|--undefined-only]
[-U|--defined-only]
[-V|--version]
[-W|--no-weak]
[-X 32_64]
[--no-demangle]
[--no-recurse-limit|--recurse-limit]]
[--plugin name]
[--size-sort]
[--special-syms]
[--synthetic]
[--target=bfdname]
[--unicode=method]
[--with-symbol-versions]
[--without-symbol-versions]
[objfile...]
DESCRIPTION
GNU nm lists the symbols from object files objfile.... If no object
files are listed as arguments, nm assumes the file a.out.
For each symbol, nm shows:
• The symbol value, in the radix selected by options (see below), or
hexadecimal by default.
• The symbol type. At least the following types are used; others
are, as well, depending on the object file format. If lowercase,
the symbol is usually local; if uppercase, the symbol is global
(external). There are however a few lowercase symbols that are
shown for special global symbols ("u", "v" and "w").
"A" The symbol's value is absolute, and will not be changed by
further linking.
"B"
"b" The symbol is in the BSS data section. This section typically
contains zero-initialized or uninitialized data, although the
exact behavior is system dependent.
"C"
"c" The symbol is common. Common symbols are uninitialized data.
When linking, multiple common symbols may appear with the same
name. If the symbol is defined anywhere, the common symbols
are treated as undefined references. The lower case c
character is used when the symbol is in a special section for
small commons.
"D"
"d" The symbol is in the initialized data section.
"G"
"g" The symbol is in an initialized data section for small objects.
Some object file formats permit more efficient access to small
data objects, such as a global int variable as opposed to a
large global array.
"i" For PE format files this indicates that the symbol is in a
section specific to the implementation of DLLs.
For ELF format files this indicates that the symbol is an
indirect function. This is a GNU extension to the standard set
of ELF symbol types. It indicates a symbol which if referenced
by a relocation does not evaluate to its address, but instead
must be invoked at runtime. The runtime execution will then
return the value to be used in the relocation.
Note - the actual symbols display for GNU indirect symbols is
controlled by the --ifunc-chars command line option. If this
option has been provided then the first character in the string
will be used for global indirect function symbols. If the
string contains a second character then that will be used for
local indirect function symbols.
"I" The symbol is an indirect reference to another symbol.
"N" The symbol is a debugging symbol.
"n" The symbol is in a non-data, non-code, non-debug read-only
section.
"p" The symbol is in a stack unwind section.
"R"
"r" The symbol is in a read only data section.
"S"
"s" The symbol is in an uninitialized or zero-initialized data
section for small objects.
"T"
"t" The symbol is in the text (code) section.
"U" The symbol is undefined.
"u" The symbol is a unique global symbol. This is a GNU extension
to the standard set of ELF symbol bindings. For such a symbol
the dynamic linker will make sure that in the entire process
there is just one symbol with this name and type in use.
"V"
"v" The symbol is a weak object. When a weak defined symbol is
linked with a normal defined symbol, the normal defined symbol
is used with no error. When a weak undefined symbol is linked
and the symbol is not defined, the value of the weak symbol
becomes zero with no error. On some systems, uppercase
indicates that a default value has been specified.
"W"
"w" The symbol is a weak symbol that has not been specifically
tagged as a weak object symbol. When a weak defined symbol is
linked with a normal defined symbol, the normal defined symbol
is used with no error. When a weak undefined symbol is linked
and the symbol is not defined, the value of the symbol is
determined in a system-specific manner without error. On some
systems, uppercase indicates that a default value has been
specified.
"-" The symbol is a stabs symbol in an a.out object file. In this
case, the next values printed are the stabs other field, the
stabs desc field, and the stab type. Stabs symbols are used to
hold debugging information.
"?" The symbol type is unknown, or object file format specific.
• The symbol name. If a symbol has version information associated
with it, then the version information is displayed as well. If the
versioned symbol is undefined or hidden from linker, the version
string is displayed as a suffix to the symbol name, preceded by an
@ character. For example foo@VER_1. If the version is the default
version to be used when resolving unversioned references to the
symbol, then it is displayed as a suffix preceded by two @
characters. For example foo@@VER_2.
OPTIONS
The long and short forms of options, shown here as alternatives, are
equivalent.
-A
-o
--print-file-name
Precede each symbol by the name of the input file (or archive
member) in which it was found, rather than identifying the input
file once only, before all of its symbols.
-a
--debug-syms
Display all symbols, even debugger-only symbols; normally these are
not listed.
-B The same as --format=bsd (for compatibility with the MIPS nm).
-C
--demangle[=style]
Decode (demangle) low-level symbol names into user-level names.
Besides removing any initial underscore prepended by the system,
this makes C++ function names readable. Different compilers have
different mangling styles. The optional demangling style argument
can be used to choose an appropriate demangling style for your
compiler.
--no-demangle
Do not demangle low-level symbol names. This is the default.
--recurse-limit
--no-recurse-limit
--recursion-limit
--no-recursion-limit
Enables or disables a limit on the amount of recursion performed
whilst demangling strings. Since the name mangling formats allow
for an infinite level of recursion it is possible to create strings
whose decoding will exhaust the amount of stack space available on
the host machine, triggering a memory fault. The limit tries to
prevent this from happening by restricting recursion to 2048 levels
of nesting.
The default is for this limit to be enabled, but disabling it may
be necessary in order to demangle truly complicated names. Note
however that if the recursion limit is disabled then stack
exhaustion is possible and any bug reports about such an event will
be rejected.
-D
--dynamic
Display the dynamic symbols rather than the normal symbols. This
is only meaningful for dynamic objects, such as certain types of
shared libraries.
-f format
--format=format
Use the output format format, which can be "bsd", "sysv", "posix"
or "just-symbols". The default is "bsd". Only the first character
of format is significant; it can be either upper or lower case.
-g
--extern-only
Display only external symbols.
-h
--help
Show a summary of the options to nm and exit.
--ifunc-chars=CHARS
When display GNU indirect function symbols nm will default to using
the "i" character for both local indirect functions and global
indirect functions. The --ifunc-chars option allows the user to
specify a string containing one or two characters. The first
character will be used for global indirect function symbols and the
second character, if present, will be used for local indirect
function symbols.
j The same as --format=just-symbols.
-l
--line-numbers
For each symbol, use debugging information to try to find a
filename and line number. For a defined symbol, look for the line
number of the address of the symbol. For an undefined symbol, look
for the line number of a relocation entry which refers to the
symbol. If line number information can be found, print it after
the other symbol information.
--inlines
When option -l is active, if the address belongs to a function that
was inlined, then this option causes the source information for all
enclosing scopes back to the first non-inlined function to be
printed as well. For example, if "main" inlines "callee1" which
inlines "callee2", and address is from "callee2", the source
information for "callee1" and "main" will also be printed.
-n
-v
--numeric-sort
Sort symbols numerically by their addresses, rather than
alphabetically by their names.
-p
--no-sort
Do not bother to sort the symbols in any order; print them in the
order encountered.
-P
--portability
Use the POSIX.2 standard output format instead of the default
format. Equivalent to -f posix.
-r
--reverse-sort
Reverse the order of the sort (whether numeric or alphabetic); let
the last come first.
-S
--print-size
Print both value and size of defined symbols for the "bsd" output
style. This option has no effect for object formats that do not
record symbol sizes, unless --size-sort is also used in which case
a calculated size is displayed.
-s
--print-armap
When listing symbols from archive members, include the index: a
mapping (stored in the archive by ar or ranlib) of which modules
contain definitions for which names.
-t radix
--radix=radix
Use radix as the radix for printing the symbol values. It must be
d for decimal, o for octal, or x for hexadecimal.
-u
--undefined-only
Display only undefined symbols (those external to each object
file). By default both defined and undefined symbols are
displayed.
-U
--defined-only
Display only defined symbols for each object file. By default both
defined and undefined symbols are displayed.
-V
--version
Show the version number of nm and exit.
-X This option is ignored for compatibility with the AIX version of
nm. It takes one parameter which must be the string 32_64. The
default mode of AIX nm corresponds to -X 32, which is not supported
by GNU nm.
--plugin name
Load the plugin called name to add support for extra target types.
This option is only available if the toolchain has been built with
plugin support enabled.
If --plugin is not provided, but plugin support has been enabled
then nm iterates over the files in ${libdir}/bfd-plugins in
alphabetic order and the first plugin that claims the object in
question is used.
Please note that this plugin search directory is not the one used
by ld's -plugin option. In order to make nm use the linker plugin
it must be copied into the ${libdir}/bfd-plugins directory. For
GCC based compilations the linker plugin is called
liblto_plugin.so.0.0.0. For Clang based compilations it is called
LLVMgold.so. The GCC plugin is always backwards compatible with
earlier versions, so it is sufficient to just copy the newest one.
--size-sort
Sort symbols by size. For ELF objects symbol sizes are read from
the ELF, for other object types the symbol sizes are computed as
the difference between the value of the symbol and the value of the
symbol with the next higher value. If the "bsd" output format is
used the size of the symbol is printed, rather than the value, and
-S must be used in order both size and value to be printed.
Note - this option does not work if --undefined-only has been
enabled as undefined symbols have no size.
--special-syms
Display symbols which have a target-specific special meaning.
These symbols are usually used by the target for some special
processing and are not normally helpful when included in the normal
symbol lists. For example for ARM targets this option would skip
the mapping symbols used to mark transitions between ARM code,
THUMB code and data.
--synthetic
Include synthetic symbols in the output. These are special symbols
created by the linker for various purposes. They are not shown by
default since they are not part of the binary's original source
code.
--unicode=[default|invalid|locale|escape|hex|highlight]
Controls the display of UTF-8 encoded multibyte characters in
strings. The default (--unicode=default) is to give them no
special treatment. The --unicode=locale option displays the
sequence in the current locale, which may or may not support them.
The options --unicode=hex and --unicode=invalid display them as hex
byte sequences enclosed by either angle brackets or curly braces.
The --unicode=escape option displays them as escape sequences
(\uxxxx) and the --unicode=highlight option displays them as escape
sequences highlighted in red (if supported by the output device).
The colouring is intended to draw attention to the presence of
unicode sequences where they might not be expected.
-W
--no-weak
Do not display weak symbols.
--with-symbol-versions
--without-symbol-versions
Enables or disables the display of symbol version information. The
version string is displayed as a suffix to the symbol name,
preceded by an @ character. For example foo@VER_1. If the version
is the default version to be used when resolving unversioned
references to the symbol then it is displayed as a suffix preceded
by two @ characters. For example foo@@VER_2. By default, symbol
version information is displayed.
--target=bfdname
Specify an object code format other than your system's default
format.
@file
Read command-line options from file. The options read are inserted
in place of the original @file option. If file does not exist, or
cannot be read, then the option will be treated literally, and not
removed.
Options in file are separated by whitespace. A whitespace
character may be included in an option by surrounding the entire
option in either single or double quotes. Any character (including
a backslash) may be included by prefixing the character to be
included with a backslash. The file may itself contain additional
@file options; any such options will be processed recursively.
SEE ALSO
ar(1), objdump(1), ranlib(1), and the Info entries for binutils.
COPYRIGHT
Copyright (c) 1991-2025 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3 or
any later version published by the Free Software Foundation; with no
Invariant Sections, with no Front-Cover Texts, and with no Back-Cover
Texts. A copy of the license is included in the section entitled "GNU
Free Documentation License".
binutils-2.44 2025-05-12 NM(1)
GPROFNG-DISPLAY-SRC(1) Команды пользователя GPROFNG-DISPLAY-SRC(1)
NAME
gprofng-display-src - Отображение исходного кода и опционально дизассемблированного кода целевого объекта
SYNOPSIS
gprofng display src [option(s)] target-file
DESCRIPTION
Отображение списка исходного кода, или исходного кода, перемешанного с кодом дизассемблирования, извлеченного из целевого файла (исполняемый файл, разделяемый объект, объектный файл или файл Java .class).
Например, эта команда отображает исходный код и список дизассемблирования для функции с именем mxv_core, которая является частью объектного файла mxv.o:
$ gprofng display src -disasm mxv_core mxv.o
Чтобы перечислить исходный код и дизассемблирование для всех функций в этом файле, используйте следующую команду:
$ gprofng display src -disasm all -1 mxv.o
Целевой файл представляет собой имя исполняемого файла, разделяемого объекта, объектного файла (.o) или файла Java .class.
Если опции не указаны, отображается список исходного кода целевого файла. Это эквивалентно -source all -1. Если эта информация недоступна, выводится соответствующее сообщение.
OPTIONS
--version
Вывести номер версии и выйти.
--help
Вывести информацию об использовании и выйти.
-functions
Перечислить все функции из данного объекта.
-source item tag
Показать исходный код для item в целевом файле. Тег используется для различия в случае нескольких вхождений с одинаковым именем. См. раздел NOTES для определения item и tag.
-disasm item tag
Включить дизассемблирование в список исходного кода. По умолчанию дизассемблирование не включается. Если исходный код недоступен, показать только список дизассемблирования. См. раздел NOTES для определения item и tag.
-outfile filename
Записать результаты в файл filename. Дефис (-) означает запись в stdout. Это значение по умолчанию. Обратите внимание, что эта опция влияет только на те опции, которые указаны справа от неё.
NOTES
Используйте item для указания имени функции, или исходного или объектного файла, который использовался для сборки исполняемого файла или разделяемого объекта.
Тег — это индекс, используемый для определения, какой item имеется в виду, когда несколько функций имеют одинаковое имя. Он обязателен, но будет игнорироваться, если не требуется для разрешения функции.
Item также может быть указан в форме function`file, в этом случае будет использован исходный код или дизассемблирование указанной функции в контексте указанного файла.
Специальная комбинация item и tag all -1 используется для указания генерации исходного кода или дизассемблирования для всех функций в целевом файле.
SEE ALSO
gprofng(1), gprofng-archive(1), gprofng-collect-app(1),
gprofng-display-html(1), gprofng-display-text(1)
Руководство пользователя для gprofng поддерживается как руководство Texinfo. Если программы info и gprofng установлены правильно, команда info gprofng должна предоставить доступ к этому документу.
COPYRIGHT
Copyright (c) 2022-2025 Free Software Foundation, Inc.
Разрешается копировать, распространять и/или изменять этот документ в соответствии с условиями Лицензии GNU Free Documentation License, версии 1.3 или любой более поздней версии, опубликованной Free Software Foundation; без Инвариантных Разделов, без Текстов Обложки и без Текстов Задней Обложки. Копия лицензии включена в раздел, озаглавленный "GNU Free Documentation License".
binutils-2.44 2025-02-02 GPROFNG-DISPLAY-SRC(1)
GPROFNG-DISPLAY-SRC(1) User Commands GPROFNG-DISPLAY-SRC(1)
NAME
gprofng-display-src - Display source code and optionally disassembly of
the target object
SYNOPSIS
gprofng display src [option(s)] target-file
DESCRIPTION
Display the source code listing, or source code interleaved with
disassembly code, as extracted from the target file (an executable,
shared object, object file, or a Java .class file).
For example, this command displays the source code and disassembly
listing for a function called mxv_core that is part of object file
mxv.o:
$ gprofng display src -disasm mxv_core mxv.o
To list the source code and disassembly for all the functions in this
file, use the following command:
$ gprofng display src -disasm all -1 mxv.o
The target-file is the name of an executable, a shared object, an
object file (.o), or a Java .class file.
If no options are given, the source code listing of the target-file is
shown. This is equivalent to -source all -1. If this information is
not available, a message to this extent is printed.
OPTIONS
--version
Print the version number and exit.
--help
Print usage information and exit.
-functions
List all the functions from the given object.
-source item tag
Show the source code for item in target-file. The tag is used to
differentiate in case there are multiple occurences with the same
name. See the NOTES section for the definition of item and tag.
-disasm item tag
Include the disassembly in the source listing. The default listing
does not include the disassembly. If the source code is not
available, show a listing of the disassembly only. See the NOTES
section for the definition of item and tag.
-outfile filename
Write results to file filename. A dash (-) writes to stdout. This
is also the default. Note that this option only affects those
options included to the right of the option.
NOTES
Use item to specify the name of a function, or of a source or object
file that was used to build the executable, or shared object.
The tag is an index used to determine which item is being referred to
when multiple functions have the same name. It is required, but will
be ignored if not necessary to resolve the function.
The item may also be specified in the form function`file`, in which
case the source or disassembly of the named function in the source
context of the named file will be used.
The special item and tag combination all -1, is used to indicate
generating the source, or disassembly, for all functions in the
target-file.
SEE ALSO
gprofng(1), gprofng-archive(1), gprofng-collect-app(1),
gprofng-display-html(1), gprofng-display-text(1)
The user guide for gprofng is maintained as a Texinfo manual. If the
info and gprofng programs are correctly installed, the command info
gprofng should give access to this document.
COPYRIGHT
Copyright (c) 2022-2025 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3 or
any later version published by the Free Software Foundation; with no
Invariant Sections, with no Front-Cover Texts, and with no Back-Cover
Texts. A copy of the license is included in the section entitled "GNU
Free Documentation License".
binutils-2.44 2025-02-02 GPROFNG-DISPLAY-SRC(1)
GPROFNG-DISPLAY-TEXT(1) Пользовательские команды GPROFNG-DISPLAY-TEXT(1)
NAME
gprofng-display-text - Отображение данных производительности в формате простого текста
SYNOPSIS
gprofng display text [option(s)] [commands] [-script script-file]
experiment(s)
DESCRIPTION
Выводит версию в формате простого текста различных отображений, поддерживаемых gprofng.
Входные данные состоят из одной или нескольких директорий экспериментов. С помощью команд пользователь управляет выводом.
Существует богатый набор команд для управления отображением данных.
Раздел NOTES перечисляет наиболее распространённые из них. Руководство пользователя gprofng перечисляет все поддерживаемые команды.
Команды, указанные в командной строке, должны предваряться символом тире ('-').
В этом примере будет показано обзор функций, за которым следует список исходного кода функции my-func, аннотированный метриками производительности, которые были записаны во время сбора данных и сохранены в директории эксперимента my-exp.er:
$ gprofng display text -functions -source my-func my-exp.er
Вместо этого, или в дополнение к этому, команды также могут быть включены в файл, называемый script-file.
Обратите внимание, что команды обрабатываются и интерпретируются слева направо, поэтому порядок имеет значение.
Если эта утилита вызывается без опций, команд или файла сценария, она запускается в режиме интерпретатора. Пользователь может вводить команды интерактивно. Сеанс завершается командой exit в интерпретаторе.
OPTIONS
--version
Вывести номер версии и выйти.
--help
Вывести информацию об использовании и выйти.
-script script-file
Выполнить команды, хранящиеся в файле сценария. Эта функция может быть объединена с командами, указанными в командной строке.
NOTES
Поддерживается множество команд. Ниже перечислены наиболее распространённые из них в основном алфавитном порядке, поскольку иногда логичнее поменять местами два пункта.
Существует ещё больше команд. Они документированы в руководстве пользователя.
"callers-callees"
В панели callers-callees показывается, какая(ие) функция(и) вызывают целевую функцию (вызывающие) и какие функции она вызывает (вызываемые). Эта команда выводит панель callers-callees для каждой из функций в порядке, определяемом метрикой сортировки функций.
"calltree"
Отобразить динамический граф вызовов из эксперимента, показывая иерархические метрики на каждом уровне.
"compare {on | off | delta | ratio}"
По умолчанию результаты для нескольких экспериментов агрегируются.
Эта команда изменяет это, чтобы включить сравнение экспериментов для определённых представлений (например, представления функций). Первый указанный эксперимент определяется как эталонный. Поддерживаются следующие опции:
"on"
Для каждого эксперимента, указанного в командной строке, выводить значения метрик, которые были активированы для эксперимента.
"off"
Отключить сравнение экспериментов. Это значение по умолчанию.
"delta"
Выводить значения для эталонного эксперимента. Результаты для других экспериментов показываются как дельта относительно эталонного (текущий-эталонный).
"ratio"
Выводить значения для эталонного эксперимента. Результаты для других экспериментов показываются как отношение относительно эталонного (текущий/эталонный).
"disasm function-name"
Вывести исходный код и инструкции для указанной функции. Инструкции аннотированы используемыми метриками.
"fsingle function-name [n]"
Вывести сводную панель для указанной функции. Необязательный параметр n требуется в тех случаях, когда несколько функций имеют одно и то же имя.
"fsummary"
Вывести сводную панель для каждой функции в списке функций.
"functions"
Отобразить список всех выполненных функций. Для каждой функции показываются используемые метрики (например, время CPU).
"header"
Показывает несколько эксплуатационных характеристик указанных экспериментов в командной строке.
"limit n"
Ограничить вывод n строками.
"lines"
Вывести список строк исходного кода и их метрик, упорядоченный по текущей метрике сортировки.
"metric_list"
Отобразить текущие выбранные метрики в представлении функций и список всех доступных метрик для целевых экспериментов.
"metrics metric-spec"
Определить метрики, которые будут отображаться в обзорах функций и callers-callees.
metric-spec может быть либо ключевым словом default для восстановления метрик по умолчанию, либо списком метрик, разделённых двоеточиями.
Специальная метрика — "hwc". Она автоматически расширяется до активного набора счётчиков аппаратных событий, использованных в экспериментах.
Если были измерены как инструкции, так и тактовые циклы, метрики "CPI" и "IPC" можно использовать для просмотра значений Clockcycles Per Instruction и Instructions Per Clockcycle соответственно.
В руководстве пользователя gprofng приведены более подробные сведения о том, как определять метрики.
"name {short | long | mangled}[:{soname | nosoname}]"
Указать, использовать ли короткую, длинную или искажённую форму имён функций. Опционально, объект загрузки, к которому относится функция, можно включить в вывод, добавив ключевое слово soname. Его также можно omitted (nosoname), что является значением по умолчанию.
Действительное различие между этими типами имён зависит от языка.
Обратите внимание, что слева и справа от двоеточия (:) не должно быть пробелов.
Не путайте эту опцию с ключевым словом name в определении метрики, которое используется для указания того, что имена функций должны отображаться в обзоре функций.
"overview"
Показывает сводку записанных данных производительности для указанных экспериментов в командной строке.
"pcs"
Вывести список счётчиков программы (PCs) и их метрик, упорядоченный по текущей метрике сортировки.
"sort metric-spec"
Сортировать список функций по указанной metric-spec.
@IndexSubentry{Sort, Reverse order} Данные можно сортировать в обратном порядке, предваряя определение метрики знаком минус (-).
Например, sort -e.totalcpu.
@IndexSubentry{Sort, Reset to default} Метрика по умолчанию для операции сортировки определена, и поскольку это постоянная команда, эту метрику по умолчанию можно восстановить с помощью "default" в качестве ключа (sort default).
"source function-name"
Вывести исходный код указанной функции, аннотированный используемыми метриками.
"viewmode {user | expert | machine}"
Эта команда актуальна только для программ на Java. Для всех других поддерживаемых языков настройка viewmode не оказывает влияния.
Поддерживаются следующие опции:
"user"
Показывать стеки вызовов Java для потоков Java, но не показывать служебные потоки. В представлении функций включена функция <JVM-System>. Это представляет агрегированное время от не-Java-потоков. В случае, если программное обеспечение JVM не сообщает стек вызовов Java, время фиксируется против функции <no Java callstack recorded>.
"expert"
Показывать стеки вызовов Java для потоков Java, когда выполняется пользовательский код Java, и стеки вызовов машины, когда выполняется код JVM или когда программное обеспечение JVM не сообщает стек вызовов Java. Показывать стеки вызовов машины для служебных потоков.
"machine"
Показывать фактические нативные стеки вызовов для всех потоков. Это режим представления для C, C++ и Fortran.
SEE ALSO
gprofng(1), gprofng-archive(1), gprofng-collect-app(1),
gprofng-display-html(1), gprofng-display-src(1)
Руководство пользователя gprofng поддерживается в виде руководства Texinfo. Если программы info и gprofng правильно установлены, команда info gprofng должна предоставить доступ к этому документу.
COPYRIGHT
Copyright (c) 2022-2025 Free Software Foundation, Inc.
Разрешается копировать, распространять и/или изменять этот документ в соответствии с условиями Лицензии GNU Free Documentation License, версии 1.3 или любой более поздней версии, опубликованной Free Software Foundation; без Инвариантных Разделов, без Текстов На Обложке и без Текстов На Задней Обложке. Копия лицензии включена в раздел, озаглавленный "GNU Free Documentation License".
binutils-2.44 2025-02-02 GPROFNG-DISPLAY-TEXT(1)
GPROFNG-DISPLAY-TEXT(1) User Commands GPROFNG-DISPLAY-TEXT(1)
NAME
gprofng-display-text - Display the performance data in plain text
format
SYNOPSIS
gprofng display text [option(s)] [commands] [-script script-file]
experiment(s)
DESCRIPTION
Print a plain text version of the various displays supported by
gprofng.
The input consists of one or more experiment directories. Through
commands, the user controls the output.
There is a rich set of commands to control the display of the data.
The NOTES section lists the most common ones. The gprofng user guide
lists all the commands supported.
Commands specified on the command line need to be prepended with the
dash ('-') symbol.
In this example, a function overview will be shown, followed by the
source code listing of function my-func, annotated with the performance
metrics that have been recorded during the data collection and stored
in experiment directory my-exp.er:
$ gprofng display text -functions -source my-func my-exp.er
Instead of, or in addition to, specifying these commands on the command
line, commands may also be included in a file called the script-file.
Note that the commands are processed and interpreted from left to
right, so the order matters.
If this tool is invoked without options, commands, or a script file, it
starts in interpreter mode. The user can then issue the commands
interactively. The session is terminated with the exit command in the
interpreter.
OPTIONS
--version
Print the version number and exit.
--help
Print usage information and exit.
-script script-file
Execute the commands stored in the script file. This feature may
be combined with commands specified at the command line.
NOTES
Many commands are supported. Below, the more common ones are listed in
mostly alphabetical order, because sometimes it is more logical to swap
the order of two entries.
There are many more commands. These are documented in the user guide.
"callers-callees"
In a callers-callees panel, it is shown which function(s) call the
target function (the callers) and what functions it is calling (the
callees). This command prints the callers-callees panel for each
of the functions, in the order specified by the function sort
metric.
"calltree"
Display the dynamic call graph from the experiment, showing the
hierarchical metrics at each level.
"compare {on | off | delta | ratio}"
By default, the results for multiple experiments are aggregated.
This command changes this to enable the comparison of experiments
for certain views (e.g. the function view). The first experiment
specified is defined to be the reference. The following options
are supported:
"on"
For each experiment specified on the command line, print the
values for the metrics that have been activated for the
experiment.
"off"
Disable the comparison of experiments. This is the default.
"delta"
Print the values for the reference experiment. The results for
the other experiments are shown as a delta relative to the
reference (current-reference).
"ratio"
Print the values for the reference experiment. The results for
the other experiments are shown as a ratio relative to the
reference (current/reference).
"disasm function-name"
List the source code and instructions for the function specified.
The instructions are annotated with the metrics used.
"fsingle function-name [n]"
Write a summary panel for the specified function. The optional
parameter n is needed for those cases where several functions have
the same name.
"fsummary"
Write a summary panel for each function in the function list.
"functions"
Display a list of all functions executed. For each function the
used metrics (e.g. the CPU time) are shown.
"header"
Shows several operational characteristics of the experiment(s)
specified on the command line.
"limit n"
Limit the output to n lines.
"lines"
Write a list of source lines and their metrics, ordered by the
current sort metric.
"metric_list"
Display the currently selected metrics in the function view and a
list of all the metrics available for the target experiment(s).
"metrics metric-spec"
Define the metrics to be displayed in the function and
callers-callees overviews.
The metric-spec can either be the keyword default to restore the
default metrics selection, or a colon separated list with metrics.
A special metric is "hwc". It automatically expands to the active
set of hardware event counters used in the experiment(s).
If both instructions and clock cycles have been measured, the "CPI"
and "IPC" metrics can be used to see the Clockcycles Per
Instruction and Instructions Per Clockcyle values, respectively.
The gprofng user guide has more details how to define metrics.
"name {short | long | mangled}[:{soname | nosoname}]"
Specify whether to use the short, long, or mangled form of function
names. Optionally, the load object that the function is part of
can be included in the output by adding the soname keyword. It can
also be ommitted (nosoname), which is the default.
Whether there is an actual difference between these types of names
depends on the language.
Note that there should be no (white)space to the left and right of
the colon (:).
This option should not be confused with the keyword name in a
metric definition, which is used to specify that the names of
functions should be shown in the function overview.
"overview"
Shows a summary of the recorded performance data for the
experiment(s) specified on the command line.
"pcs"
Write a list of program counters (PCs) and their metrics, ordered
by the current sort metric.
"sort metric-spec"
Sort the function list on the metric-spec given.
@IndexSubentry{Sort, Reverse order} The data can be sorted in
reverse order by prepending the metric definition with a minus (-)
sign.
For example sort -e.totalcpu.
@IndexSubentry{Sort, Reset to default} A default metric for the
sort operation has been defined and since this is a persistent
command, this default can be restored with "default" as the key
(sort default).
"source function-name"
List the source code for the function specified, annotated with the
metrics used.
"viewmode {user | expert | machine}"
This command is only relevant for Java programs. For all other
languages supported, the viewmode setting has no effect.
The following options are supported:
"user"
Show the Java call stacks for Java threads, but do not show
housekeeping threads. The function view includes a function
called <JVM-System>. This represents the aggregated time from
non-Java threads. In case the JVM software does not report a
Java call stack, time is reported against the function <no Java
callstack recorded>.
"expert"
Show the Java call stacks for Java threads when the user Java
code is executed, and machine call stacks when JVM code is
executed, or when the JVM software does not report a Java call
stack. Show the machine call stacks for housekeeping threads.
"machine"
Show the actual native call stacks for all threads. This is
the view mode for C, C++, and Fortran.
SEE ALSO
gprofng(1), gprofng-archive(1), gprofng-collect-app(1),
gprofng-display-html(1), gprofng-display-src(1)
The user guide for gprofng is maintained as a Texinfo manual. If the
info and gprofng programs are correctly installed, the command info
gprofng should give access to this document.
COPYRIGHT
Copyright (c) 2022-2025 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3 or
any later version published by the Free Software Foundation; with no
Invariant Sections, with no Front-Cover Texts, and with no Back-Cover
Texts. A copy of the license is included in the section entitled "GNU
Free Documentation License".
binutils-2.44 2025-02-02 GPROFNG-DISPLAY-TEXT(1)
RANLIB(1) Инструменты разработки GNU RANLIB(1)
NAME
ranlib - сгенерировать индекс для архива
SYNOPSIS
ranlib [--plugin name] [-DhHvVt] archive
DESCRIPTION
ranlib генерирует индекс содержимого архива и хранит его в архиве. Индекс перечисляет каждый символ, определяемый членом архива, который является релокуруемым объектным файлом.
Вы можете использовать nm -s или nm --print-armap для вывода этого индекса.
Архив с таким индексом ускоряет связывание с библиотекой и позволяет рутинам в библиотеке вызывать друг друга без учета их размещения в архиве.
Программа GNU ranlib является другой формой GNU ar; запуск ranlib полностью эквивалентен выполнению ar -s.
OPTIONS
-h
-H
--help
Показать информацию об использовании ranlib.
-v
-V
--version
Показать номер версии ranlib.
-D Работать в детерминированном режиме. Заголовок члена архива с картой символов будет показывать ноль для UID, GID и временной метки. При использовании этой опции несколько запусков произведут одинаковые выходные файлы.
Если binutils был настроен с опцией --enable-deterministic-archives,
то этот режим включен по умолчанию. Его можно отключить с помощью опции -U, описанной ниже.
-t Обновить временную метку карты символов архива.
-U Не работать в детерминированном режиме. Это обратное к опции -D, описанной выше: индекс архива получит реальные значения UID, GID, временной метки и режима файла.
Если binutils был настроен без опции --enable-deterministic-archives,
то этот режим включен по умолчанию.
@file
Прочитать параметры командной строки из файла. Прочитанные параметры вставляются на место оригинальной опции @file. Если файл не существует или не может быть прочитан, опция будет обработана буквально, без удаления.
Параметры в файле разделены пробелами. Пробельный символ может быть включен в параметр, если весь параметр заключить в одинарные или двойные кавычки. Любые символы (включая обратный слеш) могут быть включены путем добавления перед ними обратного слеша. Файл может сам содержать дополнительные опции @file; такие опции будут обработаны рекурсивно.
SEE ALSO
ar(1), nm(1) и записи Info для binutils.
COPYRIGHT
Copyright (c) 1991-2025 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3 or
any later version published by the Free Software Foundation; with no
Invariant Sections, with no Front-Cover Texts, and with no Back-Cover
Texts. A copy of the license is included in the section entitled "GNU
Free Documentation License".
binutils-2.44 2025-05-12 RANLIB(1)
RANLIB(1) GNU Development Tools RANLIB(1)
NAME
ranlib - generate an index to an archive
SYNOPSIS
ranlib [--plugin name] [-DhHvVt] archive
DESCRIPTION
ranlib generates an index to the contents of an archive and stores it
in the archive. The index lists each symbol defined by a member of an
archive that is a relocatable object file.
You may use nm -s or nm --print-armap to list this index.
An archive with such an index speeds up linking to the library and
allows routines in the library to call each other without regard to
their placement in the archive.
The GNU ranlib program is another form of GNU ar; running ranlib is
completely equivalent to executing ar -s.
OPTIONS
-h
-H
--help
Show usage information for ranlib.
-v
-V
--version
Show the version number of ranlib.
-D Operate in deterministic mode. The symbol map archive member's
header will show zero for the UID, GID, and timestamp. When this
option is used, multiple runs will produce identical output files.
If binutils was configured with --enable-deterministic-archives,
then this mode is on by default. It can be disabled with the -U
option, described below.
-t Update the timestamp of the symbol map of an archive.
-U Do not operate in deterministic mode. This is the inverse of the
-D option, above: the archive index will get actual UID, GID,
timestamp, and file mode values.
If binutils was configured without --enable-deterministic-archives,
then this mode is on by default.
@file
Read command-line options from file. The options read are inserted
in place of the original @file option. If file does not exist, or
cannot be read, then the option will be treated literally, and not
removed.
Options in file are separated by whitespace. A whitespace
character may be included in an option by surrounding the entire
option in either single or double quotes. Any character (including
a backslash) may be included by prefixing the character to be
included with a backslash. The file may itself contain additional
@file options; any such options will be processed recursively.
SEE ALSO
ar(1), nm(1), and the Info entries for binutils.
COPYRIGHT
Copyright (c) 1991-2025 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3 or
any later version published by the Free Software Foundation; with no
Invariant Sections, with no Front-Cover Texts, and with no Back-Cover
Texts. A copy of the license is included in the section entitled "GNU
Free Documentation License".
binutils-2.44 2025-05-12 RANLIB(1)
ELFEDIT(1) Инструменты разработки GNU ELFEDIT(1)
NAME
elfedit - обновляет ELF-заголовок и свойства программы ELF-файлов
SYNOPSIS
elfedit [--input-mach=machine]
[--input-type=type]
[--input-osabi=osabi]
[--input-abiversion=version]
--output-mach=machine
--output-type=type
--output-osabi=osabi
--output-abiversion=version
--enable-x86-feature=feature
--disable-x86-feature=feature
[-v|--version]
[-h|--help]
elffile...
DESCRIPTION
elfedit обновляет ELF-заголовок и свойства программы ELF-файлов, которые
соответствуют указанным типам ELF-машины и файлов. Опции управляют тем,
как и какие поля в ELF-заголовке и свойствах программы должны быть
обновлены.
elffile... — это ELF-файлы, которые нужно обновить. Поддерживаются 32-битные и 64-битные ELF-файлы,
а также архивы, содержащие ELF-файлы.
OPTIONS
Длинные и короткие формы опций, показанные здесь как альтернативы, эквивалентны. Должна быть указана
хотя бы одна из опций --output-mach, --output-type, --output-osabi, --output-abiversion,
--enable-x86-feature или --disable-x86-feature.
--input-mach=machine
Устанавливает совпадающий тип ELF-машины входного файла на machine. Если
--input-mach не указан, он будет совпадать с любыми типами ELF-машин.
Поддерживаемые типы ELF-машин: i386, IAMCU, L1OM, K1OM и x86-64.
--output-mach=machine
Изменяет тип ELF-машины в ELF-заголовке на machine. Поддерживаемые
типы ELF-машин такие же, как для --input-mach.
--input-type=type
Устанавливает совпадающий тип файла ELF входного файла на type. Если --input-type
не указан, он будет совпадать с любыми типами ELF-файлов.
Поддерживаемые типы ELF-файлов: rel, exec и dyn.
--output-type=type
Изменяет тип файла ELF в ELF-заголовке на type. Поддерживаемые типы
ELF такие же, как для --input-type.
--input-osabi=osabi
Устанавливает совпадающий OSABI файла ELF входного файла на osabi. Если --input-osabi
не указан, он будет совпадать с любыми OSABI ELF.
Поддерживаемые OSABI ELF: none, HPUX, NetBSD, GNU, Linux (псевдоним для GNU), Solaris, AIX, Irix,
FreeBSD, TRU64, Modesto, OpenBSD, OpenVMS, NSK, AROS и FenixOS.
--output-osabi=osabi
Изменяет OSABI в ELF-заголовке на osabi. Поддерживаемые OSABI ELF такие же, как для --input-osabi.
--input-abiversion=version
Устанавливает совпадающий ABIVERSION файла ELF входного файла на version. Значение
version должно быть между 0 и 255. Если --input-abiversion не указан,
оно будет совпадать с любыми ABIVERSION ELF.
--output-abiversion=version
Изменяет ABIVERSION в ELF-заголовке на version. Значение version должно быть
между 0 и 255.
--enable-x86-feature=feature
Устанавливает бит признака в свойствах программы для ELF-файлов типа exec или dyn
с типами машин i386 или x86-64. Поддерживаемые признаки: ibt, shstk, lam_u48 и lam_u57.
--disable-x86-feature=feature
Сбрасывает бит признака в свойствах программы для ELF-файлов типа exec или dyn
с типами машин i386 или x86-64. Поддерживаемые признаки такие же, как для --enable-x86-feature.
Примечание: опции --enable-x86-feature и --disable-x86-feature доступны
только на хостах с поддержкой mmap.
-v
--version
Выводит номер версии elfedit.
-h
--help
Выводит командные опции, которые понимает elfedit.
@file
Читает командные опции из файла. Опции из файла вставляются на место
оригинальной опции @file. Если файл не существует или не может быть прочитан,
опция будет обработана буквально, без удаления.
Опции в файле разделяются пробелами. Пробельный символ можно включить в опцию,
окружив всю опцию одинарными или двойными кавычками. Любые символы (включая
обратную косую черту) можно включить, предваряя символ обратной косой чертой.
Файл может содержать дополнительные опции @file; такие опции будут обработаны
рекурсивно.
SEE ALSO
readelf(1), а также записи Info для binutils.
COPYRIGHT
Copyright (c) 1991-2025 Free Software Foundation, Inc.
Разрешается копировать, распространять и/или изменять этот документ на условиях
Лицензии GNU Free Documentation License, версии 1.3 или любой более поздней версии,
опубликованной Free Software Foundation; без Инвариантных Разделов, без Текстов
на Обложке и без Текстов на Задней Обложке. Копия лицензии включена в раздел,
озаглавленный "GNU Free Documentation License".
binutils-2.44 2025-05-12 ELFEDIT(1)
ELFEDIT(1) GNU Development Tools ELFEDIT(1)
NAME
elfedit - update ELF header and program property of ELF files
SYNOPSIS
elfedit [--input-mach=machine]
[--input-type=type]
[--input-osabi=osabi]
[--input-abiversion=version]
--output-mach=machine
--output-type=type
--output-osabi=osabi
--output-abiversion=version
--enable-x86-feature=feature
--disable-x86-feature=feature
[-v|--version]
[-h|--help]
elffile...
DESCRIPTION
elfedit updates the ELF header and program property of ELF files which
have the matching ELF machine and file types. The options control how
and which fields in the ELF header and program property should be
updated.
elffile... are the ELF files to be updated. 32-bit and 64-bit ELF
files are supported, as are archives containing ELF files.
OPTIONS
The long and short forms of options, shown here as alternatives, are
equivalent. At least one of the --output-mach, --output-type,
--output-osabi, --output-abiversion, --enable-x86-feature and
--disable-x86-feature options must be given.
--input-mach=machine
Set the matching input ELF machine type to machine. If
--input-mach isn't specified, it will match any ELF machine types.
The supported ELF machine types are, i386, IAMCU, L1OM, K1OM and
x86-64.
--output-mach=machine
Change the ELF machine type in the ELF header to machine. The
supported ELF machine types are the same as --input-mach.
--input-type=type
Set the matching input ELF file type to type. If --input-type
isn't specified, it will match any ELF file types.
The supported ELF file types are, rel, exec and dyn.
--output-type=type
Change the ELF file type in the ELF header to type. The supported
ELF types are the same as --input-type.
--input-osabi=osabi
Set the matching input ELF file OSABI to osabi. If --input-osabi
isn't specified, it will match any ELF OSABIs.
The supported ELF OSABIs are, none, HPUX, NetBSD, GNU, Linux (alias
for GNU), Solaris, AIX, Irix, FreeBSD, TRU64, Modesto, OpenBSD,
OpenVMS, NSK, AROS and FenixOS.
--output-osabi=osabi
Change the ELF OSABI in the ELF header to osabi. The supported ELF
OSABI are the same as --input-osabi.
--input-abiversion=version
Set the matching input ELF file ABIVERSION to version. version
must be between 0 and 255. If --input-abiversion isn't specified,
it will match any ELF ABIVERSIONs.
--output-abiversion=version
Change the ELF ABIVERSION in the ELF header to version. version
must be between 0 and 255.
--enable-x86-feature=feature
Set the feature bit in program property in exec or dyn ELF files
with machine types of i386 or x86-64. The supported features are,
ibt, shstk, lam_u48 and lam_u57.
--disable-x86-feature=feature
Clear the feature bit in program property in exec or dyn ELF files
with machine types of i386 or x86-64. The supported features are
the same as --enable-x86-feature.
Note: --enable-x86-feature and --disable-x86-feature are available
only on hosts with mmap support.
-v
--version
Display the version number of elfedit.
-h
--help
Display the command-line options understood by elfedit.
@file
Read command-line options from file. The options read are inserted
in place of the original @file option. If file does not exist, or
cannot be read, then the option will be treated literally, and not
removed.
Options in file are separated by whitespace. A whitespace
character may be included in an option by surrounding the entire
option in either single or double quotes. Any character (including
a backslash) may be included by prefixing the character to be
included with a backslash. The file may itself contain additional
@file options; any such options will be processed recursively.
SEE ALSO
readelf(1), and the Info entries for binutils.
COPYRIGHT
Copyright (c) 1991-2025 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3 or
any later version published by the Free Software Foundation; with no
Invariant Sections, with no Front-Cover Texts, and with no Back-Cover
Texts. A copy of the license is included in the section entitled "GNU
Free Documentation License".
binutils-2.44 2025-05-12 ELFEDIT(1)
GPROFNG-DISPLAY-HTML(1) User Commands GPROFNG-DISPLAY-HTML(1)
NAME
gprofng-display-html - Генерация структуры каталога на основе HTML для просмотра профилей
SYNOPSIS
gprofng display html [option(s)] experiment(s)
DESCRIPTION
Обрабатывает один или несколько экспериментов для генерации каталога, содержащего файл index.html, который может быть использован для просмотра данных эксперимента.
OPTIONS
--version
Вывести номер версии и выйти.
--help
Вывести информацию об использовании и выйти.
--verbose
Включить режим подробного вывода для показа диагностических сообщений о обработке данных. По умолчанию режим подробного вывода отключен.
-d [db-vol-size], --debug[=db-vol-size]
Управлять выводом информации отладки во время выполнения для помощи в устранении неисправностей или дальнейшей разработке этого инструмента.
Параметр db-vol-size управляет объемом вывода и может быть одним из значений: s, S, m, M, l, L, xl или XL. Если db-vol-size не установлен, выводится умеренное количество информации. Это эквивалентно выбору s или S. Объем данных увеличивается по мере роста размера. Обратите внимание, что в настоящее время l/L эквивалентно xl/XL, но это может измениться в будущих обновлениях. По умолчанию режим отладки отключен.
--highlight-percentage=value
Установить процентное значение в интервале [0,100] для выделения и цветового кодирования строк исходного кода, а также инструкций, которые находятся в пределах этого процента от максимального значения метрики. По умолчанию значение составляет 90 (%). Значение ноль отключает эту функцию.
-o dirname, --output=dirname
Использовать dirname в качестве имени каталога для хранения результатов. В отсутствие этой опции по умолчанию используется имя display.<n>.html. Этот каталог создается в текущем каталоге. Число <n> — это первый положительный целочисленный номер, не используемый в этой схеме именования. Существующий каталог с таким же именем не перезаписывается. Если каталог уже существует, выводится сообщение об ошибке и инструмент завершает работу.
-O dirname, --overwrite=dirname
Использовать dirname в качестве имени каталога для хранения результатов. В отсутствие этой опции по умолчанию используется имя display.<n>.html. Этот каталог создается в текущем каталоге. Число <n> — это первый положительный целочисленный номер, не используемый в этой схеме именования. Существующий каталог с таким же именем тихо перезаписывается.
-q, --quiet
Отключить вывод всех предупреждений, сообщений отладки, подробных сообщений и любых других. Если включено, настройки для verbose и debug принимаются, но игнорируются. С этой опцией на экран выводится только информация об ошибках. По умолчанию режим тихой работы отключен.
--nowarnings
Отключить вывод сообщений предупреждений в stdout. По умолчанию сообщения предупреждений выводятся.
NOTES
- Опции и значения чувствительны к регистру.
- В этом выпуске синтаксис опций был изменен для большей совместимости с другими инструментами и командами.
Опции, которые ранее имели только значения on или off, теперь действуют как переключатели. Опция отменяет значение по умолчанию. Например, по умолчанию режим verbose отключен. Он включается с помощью опции --verbose.
Длинные опции, начинающиеся с "--", которые требуют значения, ожидают знак "=" между опцией и значением.
Хотя предыдущий синтаксис и варианты выбора все еще принимаются, мы настоятельно рекомендуем изменить использование опций в соответствии с новым синтаксисом и значениями. В какой-то момент эти устаревшие настройки могут больше не приниматься.
Для помощи в переходе выводится предупреждающее сообщение, если используется устаревший синтаксис, значение или оба.
- Опция -hp все еще принимается, но будет устаревшей в будущей версии. Используйте опцию --highlight-percentage вместо нее.
- При установке имени каталога для хранения файлов HTML убедитесь, что umask установлен на правильные разрешения доступа.
- Независимо от настройки сообщений предупреждений, если есть предупреждения, они доступны через основную страницу index.html.
- Инструмент пытается накопить как можно больше предупреждений и ошибок перед принятием действий. Таким образом, проще решить несколько проблем одновременно. В результате этого подхода сообщения могут не отображаться немедленно. В частности, предупреждения показываются в конце выполнения, но одна или несколько ошибок прерывают выполнение до начала обработки.
SEE ALSO
gprofng(1), gprofng-archive(1), gprofng-collect-app(1),
gprofng-display-src(1), gprofng-display-text(1)
Руководство пользователя для gprofng поддерживается в виде руководства Texinfo. Если программы info и gprofng установлены правильно, команда info gprofng должна предоставить доступ к этому документу.
COPYRIGHT
Copyright (c) 2022-2025 Free Software Foundation, Inc.
Разрешается копировать, распространять и/или изменять этот документ на условиях Лицензии GNU Free Documentation License, версии 1.3 или любой более поздней версии, опубликованной Free Software Foundation; без Инвариантных Разделов, без Текстов на Обложке и без Текстов на Задней Обложке. Копия лицензии включена в раздел, озаглавленный "GNU Free Documentation License".
binutils-2.44 2025-02-02 GPROFNG-DISPLAY-HTML(1)
GPROFNG-DISPLAY-HTML(1) User Commands GPROFNG-DISPLAY-HTML(1)
NAME
gprofng-display-html - Generate an HTML based directory structure to
browse the profiles
SYNOPSIS
gprofng display html [option(s)] experiment(s)
DESCRIPTION
Process one or more experiments to generate a directory containing the
index.html file that may be used to browse the experiment data.
OPTIONS
--version
Print the version number and exit.
--help
Print usage information and exit.
--verbose
Enable verbose mode to show diagnostic messages about the
processing of the data. By default verbose mode is disabled.
-d [db-vol-size], --debug[=db-vol-size]
Control the printing of run time debug information to assist with
the troubleshooting, or further development of this tool.
The db-vol-size parameter controls the output volume and is one
from the list s, S, m, M, l, L, xl, or XL. If db-vol-size is not
set, a modest amount of information is printed. This is equivalent
to select s, or S. The volume of data goes up as the size
increases. Note that currently l/L is equivalent to xl/XL, but
this is expected to change in future updates. By default debug
mode is disabled.
--highlight-percentage=value
Set a percentage value in the interval [0,100] to select and color
code source lines, as well as instructions, that are within this
percentage of the maximum metric value(s). The default is 90 (%).
A value of zero disables this feature.
-o dirname, --output=dirname
Use dirname as the directory name to store the results in. In
absence of this option, the default name is display.<n>.html. This
directory is created in the current directory. The number <n> is
the first positive integer number not in use in this naming scheme.
An existing directory with the same name is not overwritten. In
case the directory exists already, an error message is printed and
the tool terminates.
-O dirname, --overwrite=dirname
Use dirname as the directory name to store the results in. In
absence of this option, the default name is display.<n>.html. This
directory is created in the current directory. The number <n> is
the first positive integer number not in use in this naming scheme.
An existing directory with the same name is silently overwritten.
-q, --quiet
Disable the display of all warning, debug, verbose and any other
messages. If enabled, the settings for verbose and debug are
accepted, but ignored. With this option, there is no screen
output, other than errors. By default quiet mode is disabled.
--nowarnings
Disable the printing of warning messages on stdout. By default
warning messages are printed.
NOTES
- The options and values are case sensitive.
- In this release, the option syntax has changed to be more compliant
with other tools and commands.
The options that used to have an on or off value only, now act as a
switch. The option negates the default setting. For example, by
default, verbose mode is disabled. It is enabled by using the
--verbose option.
The long options, those starting with "--", that require a value,
expect the "=" sign between the option and the value.
While the previous syntax and choices are accepted still, we
strongly recommend to change the usage of the options according to
the new syntax and values. At some point, these legacy settings
may no longer be accepted.
To assist with the transition, a warning message is shown if the
legacy syntax, or value, or both, are used.
- The -hp option is still accepted, but it will be deprecated in a
future release. Use the --highlight-percentage option instead.
- When setting a directory name for the HTML files to be stored in,
make sure that umask is set to the correct access permissions.
- Regardless of the setting for the warning messages, if there are
warnings, they are accessible through the main index.html page.
- The tool tries to accumulate as many warnings and errors as
possible, before taking action. In this way, it is easier to
address multiple issues at once. As a result of this approach, it
may be that the messages do not show immediately. In particular,
warnings are shown towards the end of the execution, but one or
more errors will terminate execution before the processing begins.
SEE ALSO
gprofng(1), gprofng-archive(1), gprofng-collect-app(1),
gprofng-display-src(1), gprofng-display-text(1)
The user guide for gprofng is maintained as a Texinfo manual. If the
info and gprofng programs are correctly installed, the command info
gprofng should give access to this document.
COPYRIGHT
Copyright (c) 2022-2025 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3 or
any later version published by the Free Software Foundation; with no
Invariant Sections, with no Front-Cover Texts, and with no Back-Cover
Texts. A copy of the license is included in the section entitled "GNU
Free Documentation License".
binutils-2.44 2025-02-02 GPROFNG-DISPLAY-HTML(1)
SIZE(1) Инструменты разработки GNU SIZE(1)
NAME
size - список размеров разделов и общего размера бинарных файлов
SYNOPSIS
size [-A|-B|-G|--format=compatibility]
[--help]
[-d|-o|-x|--radix=number]
[--common]
[-t|--totals]
[--target=bfdname] [-V|--version]
[-f]
[objfile...]
DESCRIPTION
Утилита GNU size выводит размеры разделов и общий размер для каждого
из бинарных файлов objfile из списка аргументов. По умолчанию, для
каждого файла или каждого модуля, если файл является архивом,
генерируется одна строка вывода.
objfile... — это файлы, которые нужно проверить. Если ни один не
указан, будет использован файл "a.out".
OPTIONS
Параметры командной строки имеют следующее значение:
-A
-B
-G
--format=compatibility
Используя один из этих параметров, вы можете выбрать, будет ли
вывод от GNU size похож на вывод от size System V (используя -A, или
--format=sysv), или на вывод от size Berkeley (используя -B, или
--format=berkeley). Значение по умолчанию — формат в одну строку,
похожий на Berkeley. Кроме того, вы можете выбрать формат вывода GNU
(используя -G, или --format=gnu), это похоже на формат вывода
Berkeley, но размеры подсчитываются по-другому.
Вот пример формата вывода Berkeley (по умолчанию):
$ size --format=Berkeley ranlib size
text data bss dec hex filename
294880 81920 11592 388392 5ed28 ranlib
294880 81920 11888 388688 5ee50 size
В стиле вывода Berkeley только для чтения данные учитываются в
столбце "text", а не в "data", столбцы "dec" и "hex" отображаются
как сумма столбцов "text", "data" и "bss" в десятичной и
шестнадцатеричной системе соответственно.
В формате GNU только для чтения данные учитываются в столбце "data",
а не в "text", и сумма столбцов "text", "data" и "bss" отображается
только один раз, в столбце "total". Параметр --radix можно
использовать для изменения основания числа для всех столбцов. Вот те
же данные, отображаемые в соглашениях GNU:
$ size --format=GNU ranlib size
text data bss total filename
279880 96920 11592 388392 ranlib
279880 96920 11888 388688 size
Это те же данные, но отображаемые ближе к соглашениям System V:
$ size --format=SysV ranlib size
ranlib :
section size addr
.text 294880 8192
.data 81920 303104
.bss 11592 385024
Total 388392
size :
section size addr
.text 294880 8192
.data 81920 303104
.bss 11888 385024
Total 388688
--help
-h
-H
-? Показать сводку допустимых аргументов и параметров.
-d
-o
-x
--radix=number
Используя один из этих параметров, вы можете управлять тем, будет
ли размер каждого раздела указан в десятичной системе (-d, или
--radix=10); восьмеричной (-o, или --radix=8); или шестнадцатеричной
(-x, или --radix=16). В --radix=number поддерживаются только три
значения (8, 10, 16). Общий размер всегда указывается в двух
системах: десятичной и шестнадцатеричной для вывода -d или -x, или
восьмеричной и шестнадцатеричной, если используется -o.
--common
Выводить общий размер общих символов в каждом файле. При
использовании формата Berkeley или GNU они включаются в размер bss.
-t
--totals
Показывать итоги для всех перечисленных объектов (только для
режима формата Berkeley или GNU).
--target=bfdname
Указать, что формат объектного кода для objfile — bfdname. Этот
параметр может быть не нужен; size может автоматически распознавать
многие форматы.
-v
-V
--version
Вывести номер версии size.
-f Игнорируется. Этот параметр используется в других версиях
программы size, но не поддерживается в версии GNU Binutils.
@file
Читать параметры командной строки из файла. Прочитанные параметры
вставляются на место оригинального параметра @file. Если файл не
существует или не может быть прочитан, параметр будет обработан
буквально, без удаления.
Параметры в файле разделяются пробелами. Пробельный символ можно
включить в параметр, заключая весь параметр в одинарные или
двойные кавычки. Любые символы (включая обратную косую черту) можно
включить, предваряя символ обратной косой чертой. Файл может
содержать дополнительные параметры @file; такие параметры будут
обработаны рекурсивно.
SEE ALSO
ar(1), objdump(1), readelf(1), и разделы Info для binutils.
COPYRIGHT
Copyright (c) 1991-2025 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3 or
any later version published by the Free Software Foundation; with no
Invariant Sections, with no Front-Cover Texts, and with no Back-Cover
Texts. A copy of the license is included in the section entitled "GNU
Free Documentation License".
binutils-2.44 2025-05-12 SIZE(1)
SIZE(1) GNU Development Tools SIZE(1)
NAME
size - list section sizes and total size of binary files
SYNOPSIS
size [-A|-B|-G|--format=compatibility]
[--help]
[-d|-o|-x|--radix=number]
[--common]
[-t|--totals]
[--target=bfdname] [-V|--version]
[-f]
[objfile...]
DESCRIPTION
The GNU size utility lists the section sizes and the total size for
each of the binary files objfile on its argument list. By default, one
line of output is generated for each file or each module if the file is
an archive.
objfile... are the files to be examined. If none are specified, the
file "a.out" will be used instead.
OPTIONS
The command-line options have the following meanings:
-A
-B
-G
--format=compatibility
Using one of these options, you can choose whether the output from
GNU size resembles output from System V size (using -A, or
--format=sysv), or Berkeley size (using -B, or --format=berkeley).
The default is the one-line format similar to Berkeley's.
Alternatively, you can choose the GNU format output (using -G, or
--format=gnu), this is similar to Berkeley's output format, but
sizes are counted differently.
Here is an example of the Berkeley (default) format of output from
size:
$ size --format=Berkeley ranlib size
text data bss dec hex filename
294880 81920 11592 388392 5ed28 ranlib
294880 81920 11888 388688 5ee50 size
The Berkeley style output counts read only data in the "text"
column, not in the "data" column, the "dec" and "hex" columns both
display the sum of the "text", "data", and "bss" columns in decimal
and hexadecimal respectively.
The GNU format counts read only data in the "data" column, not the
"text" column, and only displays the sum of the "text", "data", and
"bss" columns once, in the "total" column. The --radix option can
be used to change the number base for all columns. Here is the
same data displayed with GNU conventions:
$ size --format=GNU ranlib size
text data bss total filename
279880 96920 11592 388392 ranlib
279880 96920 11888 388688 size
This is the same data, but displayed closer to System V
conventions:
$ size --format=SysV ranlib size
ranlib :
section size addr
.text 294880 8192
.data 81920 303104
.bss 11592 385024
Total 388392
size :
section size addr
.text 294880 8192
.data 81920 303104
.bss 11888 385024
Total 388688
--help
-h
-H
-? Show a summary of acceptable arguments and options.
-d
-o
-x
--radix=number
Using one of these options, you can control whether the size of
each section is given in decimal (-d, or --radix=10); octal (-o, or
--radix=8); or hexadecimal (-x, or --radix=16). In --radix=number,
only the three values (8, 10, 16) are supported. The total size is
always given in two radices; decimal and hexadecimal for -d or -x
output, or octal and hexadecimal if you're using -o.
--common
Print total size of common symbols in each file. When using
Berkeley or GNU format these are included in the bss size.
-t
--totals
Show totals of all objects listed (Berkeley or GNU format mode
only).
--target=bfdname
Specify that the object-code format for objfile is bfdname. This
option may not be necessary; size can automatically recognize many
formats.
-v
-V
--version
Display the version number of size.
-f Ignored. This option is used by other versions of the size
program, but it is not supported by the GNU Binutils version.
@file
Read command-line options from file. The options read are inserted
in place of the original @file option. If file does not exist, or
cannot be read, then the option will be treated literally, and not
removed.
Options in file are separated by whitespace. A whitespace
character may be included in an option by surrounding the entire
option in either single or double quotes. Any character (including
a backslash) may be included by prefixing the character to be
included with a backslash. The file may itself contain additional
@file options; any such options will be processed recursively.
SEE ALSO
ar(1), objdump(1), readelf(1), and the Info entries for binutils.
COPYRIGHT
Copyright (c) 1991-2025 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3 or
any later version published by the Free Software Foundation; with no
Invariant Sections, with no Front-Cover Texts, and with no Back-Cover
Texts. A copy of the license is included in the section entitled "GNU
Free Documentation License".
binutils-2.44 2025-05-12 SIZE(1)