Dynamic linking

From Linuxintro
Revision as of 12:16, 31 December 2010 by imported>ThorstenStaerk (New page: This is an example how you get your own dynamic linked library and a program that uses it. The only thing you will need to is to install gcc: cat > main.cpp << EOF #include <ios...)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

This is an example how you get your own dynamic linked library and a program that uses it. The only thing you will need to is to install gcc:

cat > main.cpp << EOF
#include <iostream>
#include <dlfcn.h> 

extern "C" void help(); 

int main() 
{
  help();
  return 0;
}
EOF

We have now created your main program. It contains a declaration of the function help(), but no implementation. The program does nothing more than to call the function help(), notably, without knowing about its implementation.

cat > help.cpp << EOF
#include <iostream>

extern "C" void help() 
{
  std::cout << "hello world" << '\

';

}
EOF

We have now created your library. It implements the function help().

gcc help.cpp -o libhelp.so -ldl -shared -fPIC

We have now built your library, help.so

g++ main.cpp -lhelp

Now we have built an executable a.out that uses a library libhelp.so. This looks for me like this:

tweedleburg:~/test # ldd a.out
        linux-vdso.so.1 =>  (0x00007fff6dffe000)
        libhelp.so => not found
        libstdc++.so.6 => /usr/lib64/libstdc++.so.6 (0x00007fec65a02000)
        libm.so.6 => /lib64/libm.so.6 (0x00007fec657ac000)
        libgcc_s.so.1 => /lib64/libgcc_s.so.1 (0x00007fec65595000)
        libc.so.6 => /lib64/libc.so.6 (0x00007fec6523c000)
        /lib64/ld-linux-x86-64.so.2 (0x00007fec65d0e000)

Of course we cannot get it running:

tweedleburg:~/test # ./a.out
./a.out: error while loading shared libraries: libhelp.so: cannot open shared object file: No such file or directory

Without the correct path to search the libraries:

tweedleburg:~/test # export LD_LIBRARY_PATH=.
tweedleburg:~/test # ./a.out
hello world