Choosing Archive or Shared Libraries with -a

If both an archive and shared version of a particular library reside in the same directory, ld links with the shared version. Occasionally, you might want to override this behavior.

As an example, suppose you write an application that runs on a system on which shared libraries may not be present. Since the program cannot run without the shared library, it would be best to link with the archive library resulting in executable code that contains the required library routines. See also“Caution When Mixing Shared and Archive Libraries” (page 118)

Option Settings to -a

The -a option tells the linker what kind of library to link with. It applies to all libraries (-l options) until the end of the command line or until the next -a option. Its syntax is:

-a {archive shared default archive_shared shared_archive}

The different option settings are:

-a archive

Select archive libraries. If the archive library does not exist, ld generates an

 

error message and does not generate the output file.

-a ar-a shared chive

Select shared libraries. If the shared library does not exist, ld

 

 

generates an error message and does not generate the output file.

-a default

This is the same as -a shared_archive.

-a archive_shared

Select the archive library if it exists; otherwise, select the shared library.

 

 

If the library is not found in either version, ld generates an error

 

 

message and does not generate the output file.

-a shared_archive

Select the shared library if it exists; otherwise, select the archive library.

 

 

If the library is not found in either version, ld generates an error

 

 

message and does not generate the output file.

The -a shared and -a archive options specify only one type of library to use. An error results if that type is not found. The other three options specify a preferred type of library and an alternate type of library if the preferred type is not found.

CAUTION: You must avoid mixing shared libraries and archive libraries in the same application. For more information, see “Caution When Mixing Shared and Archive Libraries” (page 118)

Example Using -a

The following command links with the archive versions of libcurses, libm, and libc:

$ ld /opt/langtools/lib/hpux32/crt0.o prog.o -a archive -lcurses -lm -lc

Linking Shared Libraries with -dynamic

Use the -dynamicoption to instruct the linker to look for shared libraries first and then archive libraries. The linker outputs a share-bound executable.

This option is on by default.

For example:

$ ld main.o -dynamic -L. -lbar -lc

is the same as:

$ ld main.o -L. -lbar -lc

If you specified an archive library, the linker links it in, but the resulting executable is still a share-bound executable. This is true even if the linker finds no shared libraries at link time.

36 Determining How to Link Programs or Libraries (Linker Tasks)