Overloading a "library"

X

Xavier Decoret

This is a bit *nix related but it still should be suitable for that
newsgroup.

I would like to "overload" a function that is defined in a library. Here
is a dummy example. Let's say I want to find out in my program how many
time the sqrtf() function of libm.a is called.

I would like to define:

unsigned int nbCalls = 0;

inline float
my_sqrtf(const float f)
{
++nbCalls;
return sqrtf(f);
}

Using the my_ naming scheme forces me to change my program's code
(probably using a PREFIX macro that can be set to my_ or to nothing to
be able to compile both versions). But then I have to recompile, which
is a burden because I might have many libraries dependency using the
sqrtf function.

An approach would be to create a my_libm.a where I redefine my version
of sqrtf() and link with that lib instead of libm.a.

The problem is then: how can I, in this library, call the original
sqrtf() function? I cannot link it with libm.a because I would get a
multiple defined symbol problem, right?

I was wondering if anyone on this newsgroup have been tampering with
this. If yes, any hint would be greatly appreciated!


--
+-------------------------------------------------+
| Xavier Décoret - Post Doct |
| Graphics Lab (LCS) - MIT |
| mailto: (e-mail address removed) |
| home : http://www.graphics.lcs.mit.edu/~decoret|
+-------------------------------------------------+
 
J

Jerry Coffin

[ ... ]
I would like to "overload" a function that is defined in a library. Here
is a dummy example. Let's say I want to find out in my program how many
time the sqrtf() function of libm.a is called.

I'd use namespaces:

namespace instrumented {
float sqrtf(float arg) {
++nbCalls;
return std::sqrt(arg);
}
};

In serious code, I'd generally advise against using most namespace names
directly. If you use a namespace alias instead, this sort of change
becomes trivial. e.g. if you started with:

float x = std::sqrtf(2.0f);

It would be fairly difficult to change things. OTOH, if you started
with:

namespace lib = std;

float x = lib::sqrtf(2.0f);

Then changing to a totally different set of functions becomes trivial:

namespace lib = instrumented;

and the remaining code stays the same.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,773
Messages
2,569,594
Members
45,119
Latest member
IrmaNorcro
Top