tags:

views:

122

answers:

1

What should I do to implement a hook-like system?
This is my setup:

I have these static libraries:

  • A.lib
  • B.lib

A and B are like modules that can be included together within a same application. The thing is I have a function in A that I want to expose to B. I was doing this with a callback list... but I'm not comfortable with this idea. So I think I can implement a hooking-like system, like Win32API has, but I want to hear an opinion from an expert.

Of course, I have access to both source-codes.

NOTE: I forgot to mention that I'm NOT using classes, and I can't create a class or object for this project, because of a design decision, so something like inheritance is not allowed here.

+2  A: 

Have you considered moving the shared portion out into a third library?

A hooking mechanism wouldn't be much of a win in a strictly statically linked scenario -- a shared dependency with an extra helping of dynamic complication. If you have a place to put the hook that both your libraries can get to, just put the function there instead.

Alternatively, just export the function from library A, reference it from library B, perhaps ensure the libraries are linked in the correct order, and the linker should sort it out for you.

If library A may or may not be linked, and your toolchain supports it, you can declare a dummy version of the function in B as a weak symbol which is overridden if A is linked.

Jeffrey Hantin
Thanks for the quick reply. Yes I did, but the thing is I want to expose only this function, so I see pointless to generate an additional dependency to the application, only because of a function.
Veehmot
A hooking mechanism wouldn't be much of a win then -- a shared dependency with an extra helping of dynamic complication. If you have a place to put the hook that both your libraries can get to, just put the function there instead.
Jeffrey Hantin
I see your point now. This is a good approach, however I will wait for other answers. I will be glad with a compilation-time solution, like replacing function or something like that, taking advantage of using static libraries.
Veehmot
Great approach with weak symbols!! ... VS doesn't support them, tough :(
Veehmot
+1 for the weak symbol idea. I had never heard of such a creature.
Jere.Jones