Команда 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 command in Linux with Examples
ranlib command in Linux is used to generate index to archive. ranlib generates an index to the contents of an archive and it will be stored in the archive. The index lists each symbol defined by a member of an archive which is simply relocatable object file. You may use nm -s or nm –print-armap to list all of this index. An archive with such an index speeds up the 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 running ar -s.
Syntax:
Example: It will generate index to archive as shown in the below example.
Explanation: As you can see in above example we are archiving three files named main.o, point.o and rectangle.o to fruits.a and then using ranlib command generating an index to the contents of an archive and it will be stored in the archive.
Options:
- –help: This option will show usage information for ranlib.
–version: This option will show the version number of ranlib.
-D : This option will operate in deterministic mode. The symbol map archive of member’s header will show zero for the UID, GID, and timestamp. When this option is being used, multiple runs will produce identical output files.
Example:
Explanation: As you can see in above example we are archiving three files named main.o, point.o and rectangle.o to fruits.a and then using ranlib command with the option -D we are changing the mode of operation to deterministic and generating an index to the contents of an archive and it will stores it in the archive.
-t : This option will update the timestamp of the symbol map of an archive.
Example :
-U: This option do not operate in deterministic mode. This is exactly the inverse of the -D option. The archive index will get actual UID, GID, timestamp, and file mode values. If binutils was configured without using –enable-deterministic-archives, then this mode is set by default.
Источник
ranlib(1) — Linux man page
ranlib — generate index to archive.
Synopsis
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
-V —version Show the version number of ranlib. -t
Update the timestamp of the symbol map of an 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
ar(1), nm(1), and the Info entries for binutils.
Copyright
Copyright В© 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 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».
Источник
what is ranlib?
I have been using a MacOSX system for a while, but just only recently started poking into the guts. I found a guide telling me to run ‘sudo ranlib /usr/local/lib/libjpeg.a'(installing libjpeg). I have read the ranlib manual, and tried looking online on it. I simply don’t understand. What resources do I need to look up to learn more, or can someone give a concise explanation on its use? Thanks in advance!
4 Answers 4
ranlib adds or updates object files in a static library. Linkers can use static libraries when linking in order to provide symbols that the code needs in order to operate (as opposed to the loader looking for them in dynamic libraries when running the executable).
So if you archive a collection of object files, say:
creates an index of the contents of fruits.a and stores the index in fruits.a. This is useful for linking and in case the objects call each other.
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. 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.
source: ranlib man page
ar
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.
ld
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):
Источник