Меню Рубрики

Ranlib linux что это

Команда ranlib в Linux с примерами

Команда ranlib в Linux используется для генерации индекса в архив. ranlib создает индекс содержимого архива, и он будет храниться в архиве. Индекс перечисляет каждый символ, определенный членом архива, который является просто перемещаемым объектным файлом. Вы можете использовать nm -s или nm -print-armap для отображения всего этого индекса. Архив с таким индексом ускоряет связь с библиотекой и позволяет подпрограммам в библиотеке вызывать друг друга независимо от их размещения в архиве. Программа GNU ranlib — это другая форма GNU ar; Запуск ranlib полностью эквивалентен запуску ar -s .

Синтаксис:

Пример: будет создан индекс для архивирования, как показано в следующем примере.

Объяснение: Как вы можете видеть в приведенном выше примере, мы архивируем три файла с именами main.o , point.o и rectangle.o на fruits.a, а затем с помощью команды ranlib создаем индекс содержимого архива, и он будет храниться в архив.

Параметры:

    –Help: эта опция покажет информацию об использовании для ranlib.

–Version: эта опция покажет номер версии ranlib .

-D: эта опция будет работать в детерминированном режиме. В архиве символьных карт заголовка участника будет отображаться ноль для UID, GID и отметки времени. Когда эта опция используется, несколько прогонов будут производить идентичные выходные файлы.

Пример:

Объяснение: Как вы можете видеть в приведенном выше примере, мы архивируем три файла с именами main.o , point.o и rectangle.o на fruits.a, а затем с помощью команды ranlib с параметром -D мы меняем режим работы на детерминированный и создание индекса для содержимого архива, и он будет хранить его в архиве.

-t: эта опция обновит временную метку карты символов архива.

Пример :

-U: эта опция не работает в детерминированном режиме. Это как раз обратная опция -D. Индекс архива получит фактические значения UID, GID, метки времени и режима файла. Если binutils был настроен без использования –enable -terministic-archives , то этот режим устанавливается по умолчанию.

Источник

Ranlib linux что это

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

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


COPYRIGHT

Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.1 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».

Источник

Ranlib linux что это

Для создания статических библиотек существует специальная простая программа называемая ar (сокр. от archiver — архиватор). Она используется для создания, модификации и просмотра объектных файлов в статических библиотеках, которые в действительности представляют из себя простые архивы.

Давайте вернемся к проекту из шага «Шаг 3 — Компиляция нескольких файлов» и создадим из файлов f1.c и f2.c отдельную библиотеку. Для начала компилируем эти файлы:

В результате получим, как обычно, два файла — f1.o и f2.o. Для того, чтобы создать библиотеку из объектых файлов надо вызвать программу ar со следующими параметрами:

Допустим наша библиотека будет называться fs, тогда команда запишется в виде:

В результате получим файл libfs.a, в котором будут лежать копии объектых файлов f1.o и f2.o. Если файл библиотеки уже существует, то архиватор будет анализировать содержимое архива, он добавит новые объектные файлы и заменит старые обновленными версиями. Опция c заставляет создавать (от create) библиотеку, если ее нет, а опция r (от replace) заменяет старые объектные файлы новыми версиями.

Пока у нас есть лишь архивный файл libfs.a. Чтобы из него сделать полноценную библиотеку объектных файлов надо добавить к этому архиву индекс символов, т.е. список вложенных в библиотеку функций и переменных, чтобы линковка происходила быстрее. Далается это командой:

Программа ranlib добавит индекс к архиву и получится полноценная статическая библиотека объектных файлов. Стоит отметить, что на некоторых системах программа ar автоматически создает индекс, и использование ranlib не имеет никакого эффекта. Но тут надо быть осторожным при атоматической компиляции библиотеки с помощью файлов makefile, если вы не будете использовать утилиту ranlib, то возможно на каких-то системах библиотеки будут создаваться не верно и потеряется независимость от платформы. Так что возьмем за правило тот факт, что утилиту ranlib надо запускать в любом случае, даже если он нее нет никакого эффекта.

Для компиляции нашего основного файла main.c надо сообщить компилятору, что надо использовать библиотеки. Чтобы компилятор знал где искать библиотеки ему надо сообщить каталог, в котором они содержатся и список этих билиотек. Каталог с библиотеками указывается ключом -L, в нашем случае библиотека находится в текущем каталоге, значит путь до нее будет в виде точки (-L.). Используемые библиотеки перечисляются через ключ -l, после которого указывается название библиотеки без префикса lib и окончания .a. В нашем случае этот ключ будет выглядеть, как -lfs. Теперь все одной командой:

Или можно чуть короче:

Заметьте, что компилятору нужны библиотеки на этапе создания конечного файла, т.е. линковки. В первом случае процесс компиляции совершается первой командой, а сборка файла второй командой. Если же мы попытаемся подсунуть библиотеку на этапе компиляции, то получим вежливый ответ:

Источник

what is the difference between ranlib, ar, and ld for making libraries

To make libraries in c++/unix from *.o files, I have noticed two different ways in my project (legacy code):

What is the difference between the two approaches, and which is to be used for what purpose?

1 Answer 1

In Linux, ar is the GNU general purpose archiver. (There are non-GNU variants of ar in other Unix-like OSes). With the option c

It creates an archive containing copies of file. . The archive-name conventionally but not necessarily has the extension .a (for archive). Each file. may be any kind of file whatever, not necessarily an object file.

When the archived files are all object files it is usually the intention to use the archive for delivering that selection of object files into the linkage of programs or DSOs (Dynamic Shared Objects). In this case archive-name will also conventionally be given the prefix lib , e.g. libfoo.a , so that it can be discovered as a candidate linker input file via the linker option -lfoo .

Used as a linker input file, libfoo.a is normally called a static library. This usage is a perpetual source of confusion to inexpert programmers, because it leads them to think that an archive libfoo.a is much the same kind of thing as a DSO, libfoo.so , normally called a dynamic/shared library, and to build false expectations on this basis. In fact a «static library» and a «dynamic library» are not at all similar things and are used in linkage in utterly different ways.

A conspicuous difference is that a static library is not produced by the linker, but by ar . So no linkage happens, no symbol resolution happens. The archived object files are unchanged: they’re just put in a bag.

When an archive is input in the linkage of something that is produced by the linker — such as a program or DSO — the linker looks in the bag to see if there are any object files in it that provide definitions for unresolved symbol references that have accrued earlier in the linkage. If it finds any, it extracts those object files from the bag and links them into the output file, exactly as if they were named individually in the linker commandline and the archive not mentioned at all. So the entire role of an archive in linkage is as bag of object files from which the linker can select the ones it needs to carry on the linkage.

By default, GNU ar makes its output archives ready for use as linker inputs. It adds a phony «file» to the archive, with a magic phony filename, and in this phony file it writes content that the linker is able to read as a lookup table from the global symbols that are defined by any object files in the archive to the names and positions of those object files in the archive. This lookup table is what enables the linker to look in the archive and identify any object files that define any unresolved symbol references it has got in hand.

You can suppress the creation or updating of this lookup table with the q ( = quick) option — which in fact you’ve used in your own ar example — and also with the (capital) S ( = no symbol table) option. And if you invoke ar to create or update an archive that hasn’t got (an uptodate) symbol table for any reason, then you can give it one with the s option.

ranlib

ranlib doesn’t create libraries at all. In Linux, ranlib is a legacy program that adds an (uptodate) symbol table to an ar archive if it doesn’t have one. It’s effect is exactly the same as ar s , with GNU ar . Historically, before ar was equipped to generate a symbol table itself, ranlib was the kludge that injected the magic phony file into an archive to enable the linker to pick object files out of it. In non-GNU Unix-like OSes, ranlib might still be needed for this purpose. Your example:

  • Create libgraphics.a by appending to an archive all *.o files in the current directory, with no symbol table.
  • Then add a symbol table to libgraphics.a

In linux, this has the same net effect as:

By itself, ar qc libgraphics.a *.o , creates an archive that the linker can’t use, because it has no symbol table.

is actually quite unorthodox. This illustrates the fairly rare use of the linker, ld , to produce a merged object file by linking multiple input files into a single output object file, in which symbol resolution has been done as far as is possible, given the input files. The -r ( = relocatable) option directs the linker to produce an object file target (rather than a program, or DSO) by linking the inputs as far as possible and not to fail the linkaqe if undefined symbol references remain in the output file. This usage is called partial linking.

The output file of ld -r . is an object file, not an ar archive, and specifying an output filename that looks like that of an ar archive doesn’t make it one. So your example illustrates a deception. This:

would be truthful. It’s unclear to me what the purpose of a such a deception could be, because even if an ELF object file is called libgraphics.a , and is input to a linkage either by that name, or by -lgraphics , the linker will correctly identify it as an ELF object file, not an ar archive, and will consume it the way it consumes any object file in the commandline: it links it unconditionally into the output file, whereas the point of inputting a genuine archive is to link archive members only on condition that they are referenced. Perhaps you just have an example of ill-informed linking here.

Wrapping up.

We’ve actually only seen one way of producing something that is conventionally called a library, and that’s the production of a so-called static library, by archiving some object files and putting a symbol table in the archive.

And we haven’t seen at all how to produce the other and most important kind of thing that’s conventionally called a library, namely a Dynamic Shared Object/shared library/dynamic library.

Like a program, a DSO is produced by the linker. A program and a DSO are variants of ELF binary that the OS loader understands and can use to assemble a running process. Usually we invoke the linker via one one of the GCC frontends ( gcc , g++ , gfortran , etc):

Источник

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

Ваш адрес email не будет опубликован. Обязательные поля помечены *

  • Операционные системы mac os используются на компьютерах выпускаемых фирмой
  • Операционная система похожая на mac os
  • Операционная система mac os установка
  • Операционная система mac os преимущества и недостатки
  • Операционная система mac os краткое описание