Reputation: 983
#include <stdio.h>
int main()
{
printf("%s","Hello world");
return 0;
}
$gcc -o hello hello.c
Question:
1 - I believe the printf function's object file is statically linked. Is that correct?
2 - How should I configure/write this code so that the library files are dynamically linked or I mean it uses shared libraries at runtime?
Note: I am beginner in this concept, so feel free to correct me wherever it doesn't makes sense
Upvotes: 0
Views: 640
Reputation: 74088
The linker takes whatever it finds. This is usually the shared library.
On a Linux system, you can use
file hello
to find out, whether it is linked statically or dynamically.
E.g.
file /bin/bash
gives
/bin/bash: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.24, BuildID[sha1]=0x6dafe33f9353cbb054b1b1f7b079545992575757, stripped
whereas
file /bin/busybox
gives
/bin/busybox: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), statically linked, for GNU/Linux 2.6.24, BuildID[sha1]=0xac4943b7daf7c3c204a2866ea5398f2337ff93c9, stripped
You can force a static link, by adding the -static
option to gcc
gcc -static -o hello hello.c
file hello
/tmp/hello: ELF 64-bit LSB executable, x86-64, version 1 (GNU/Linux), statically linked, for GNU/Linux 2.6.24, BuildID[sha1]=0x790ec9b287fd2a276162560e5e6669ba6b73e68f, not stripped
Update:
Linking is the process of putting object files, dynamic and static libraries and some boilerplate objects together, to form a binary executable file.
You can use both dynamic and static libraries in one executable. The needed object files of a static library are copied into the executable. On the other side, dynamic libraries (dynamic objects actually) are not copied, but rather referenced by the resulting binary.
Update:
There are two kinds of libraries, static libraries (ar archives, see man ar
)
file /usr/lib/libnet.a
/usr/lib/libnet.a: current ar archive
and dynamic libraries (dynamic objects)
file /usr/lib/libnet.so.1.5.0
/usr/lib/libnet.so.1.5.0: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, BuildID[sha1]=0x0c596357947e79001025b3c57be933690085dffb, stripped
You can have both types of library installed at the same time, e.g.
ls -l /usr/lib/libnet.*
-rw-r--r-- 1 root root 207780 Okt 28 2011 /usr/lib/libnet.a
-rw-r--r-- 1 root root 802 Okt 28 2011 /usr/lib/libnet.la
lrwxrwxrwx 1 root root 15 Okt 28 2011 /usr/lib/libnet.so -> libnet.so.1.5.0
lrwxrwxrwx 1 root root 15 Okt 28 2011 /usr/lib/libnet.so.1 -> libnet.so.1.5.0
-rw-r--r-- 1 root root 92712 Okt 28 2011 /usr/lib/libnet.so.1.5.0
An ar
archive contains one or more object files, which are selected by the linker if needed by the executable file. A shared object is an object with subroutines, which allows to be called by other shared objects or executables at runtime.
If you're interested in this subject, you can also look at this Wikipedia - Library (computing) article.
Upvotes: 3