Previous Next Contents

3. Building programs in ELF

3.1 Ordinary programs

To build a program in ELF, use gcc as always. To build in a.out, use gcc -b i486-linuxaout .


$ cat >hello.c
main() { printf("hello, world\n"); }
^D
$ gcc -o hello hello.c
$ file hello
hello: ELF 32-bit LSB executable i386 (386 and up) Version 1
$ ./hello
hello, world

This is perhaps an appropriate time to answer the question ``if a.out compilers default to producing a program called a.out, what name does an ELF compiler give its output?''. Still a.out, is the answer. Boring boring boring ... :-)

3.2 Building libraries

To build libfoo.so as a shared library, the basic steps look like this:


$ gcc -fPIC -c *.c
$ gcc -shared -Wl,-soname,libfoo.so.1 -o libfoo.so.1.0 *.o
$ ln -s libfoo.so.1.0 libfoo.so.1
$ ln -s libfoo.so.1 libfoo.so
$ export LD_LIBRARY_PATH=`pwd`:$LD_LIBRARY_PATH

This will generate a shared library called libfoo.so.1.0, and the appropriate links for ld (libfoo.so) and the dynamic linker (libfoo.so.1) to find it. To test, we add the current directory to LD_LIBRARY_PATH.

When you're happpy that the library works, you'll have to move it to, say, /usr/local/lib, and recreate the appropriate links. Note that the libfoo.so link should point to libfoo.so.1, so it doesn't need updating on every minor version number change. The link from libfoo.so.1 to libfoo.so.1.0 is kept up to date by ldconfig, which on most systems is run as part of the boot process.


$ su
# cp libfoo.so.1.0 /usr/local/lib
# /sbin/ldconfig
# ( cd /usr/local/lib ; ln -s libfoo.so.1 libfoo.so )

3.3 Programs with dynamic loading

These are covered extensively in H J Lu's ELF programming document, and the dlopen(3) manual page, which can be found in the ld.so package. Here's a nice simple example though: link it with -ldl


#include <dlfcn.h>
#include <stdio.h>

main()
{
  void *libc;
  void (*printf_call)();

  if(libc=dlopen("/lib/libc.so.5",RTLD_LAZY))
  {
    printf_call=dlsym(libc,"printf");
    (*printf_call)("hello, world\n");
  }

}

3.4 Debugging

Your existing copy of gdb will most likely work unchanged with ELF programs. The new version in the GCC directory on tsx-11 is reported to be better at debugging programs that use shared libraries and dynamic loading, and to understand ELF core dumps.

Note that 1.2 series kernels cannot generate core dumps from ELF programs anyway. 1.3 can.


Previous Next Contents