Difference between revisions of "Dynamic linking"
imported>ThorstenStaerk |
imported>ThorstenStaerk m (little migration fail ;)) |
||
(One intermediate revision by the same user not shown) | |||
Line 18: | Line 18: | ||
extern "C" void help() | extern "C" void help() | ||
{ | { | ||
− | std::cout << "hello world" << '\ | + | std::cout << "hello world" << '\'; |
− | '; | ||
} | } | ||
EOF | EOF | ||
Line 46: | Line 45: | ||
tweedleburg:~/test # | tweedleburg:~/test # | ||
And if we disassemble the executable file, we see a call to the function help: | And if we disassemble the executable file, we see a call to the function help: | ||
− | tweedleburg:~/test # objdump -d a.out | grep help | + | tweedleburg:~/test # [[objdump]] -d a.out | [[grep]] help |
00000000004006b8 <help@plt>: | 00000000004006b8 <help@plt>: | ||
4007b8: e8 fb fe ff ff callq 4006b8 <help@plt> | 4007b8: e8 fb fe ff ff callq 4006b8 <help@plt> |
Latest revision as of 21:13, 14 December 2014
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. As search path for libraries (-L) also the current path (.) shall be used:
g++ main.cpp -lhelp -L.
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
But the string hello world is not contained in the executable file:
tweedleburg:~/test # strings a.out | grep hello tweedleburg:~/test #
And if we disassemble the executable file, we see a call to the function help:
tweedleburg:~/test # objdump -d a.out | grep help 00000000004006b8 <help@plt>: 4007b8: e8 fb fe ff ff callq 4006b8 <help@plt>