3

I have a program which is to be used with a shared library.

I have one library (1) that is compiled with the methods full of code i.e.

class A
{
public:
    int* funcA(int a, int b)
    {
        int* pInt = new int;
        *pInt = a + (b * 20);
        return pInt;
    }
};

Then I have another library (2) with exactly the same name and interface with nothing in the methods i.e. a dummy class

class A
{
public:
    int* funcA(int a, int b)
    {
        return 0;
    }
};

(note: code just used to illustrate my problem)

If I compile against library 1 and then use library 1 at runtime, everything works as expected.

If I compile against library 2 and then use library 1 at runtime, the first called to funcA dies.

If I used nm -D libMy.so and look at the offset of funcA at runtime, it is different. Is this included in the binary?

Ive read various manuals and tutorials but am none the wiser as to how the compilation and runtime aspect causes this failure. I would have thought the interface is the same so the method would succeed.

Thanks.

pstrjds
  • 16,840
  • 6
  • 52
  • 61
embeddedbob
  • 83
  • 1
  • 6
  • When you say "compiled against", do you mean you have linked against the lib file for library 1 or library 2? In that case, you have to use the `library.so` file you linked against. – pstrjds Aug 30 '12 at 15:12
  • Sorry, yes I mean linked against library 2 and using library 1. I am interested in the reason why it fails. – embeddedbob Aug 30 '12 at 15:17

3 Answers3

3

The reason this is failing is that you have linked against a different library and thus (as you have seen) the function offsets are different. The linker has placed the offsets into your compiled binary and so it will only run against that library. In order to accomplish what you are attempting here you will need to use dynamic library loading see this SO question for more info.

EDIT:
With a little further reading, I came across this PDF, you may find it helpful.

Community
  • 1
  • 1
pstrjds
  • 16,840
  • 6
  • 52
  • 61
0

(I don't have enough rep to just make a comment below your question)

This might be because the program is prelinked (Linux) or prebinded (MacOS) although I am not 100% sure. Some basic info about it on wikipedia below. Have you encountered this on your searches through the manuals?

http://en.wikipedia.org/wiki/Prelink

http://en.wikipedia.org/wiki/Prebinding

Fszczemton
  • 471
  • 3
  • 5
0

Did you forget a -fPIC option while compiling libraries? Please, add compilation commands.

Pavel Ognev
  • 962
  • 7
  • 15