Overloading a "library"

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Xavier Decoret

    Overloading a "library"

    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: decoret@graphic s.lcs.mit.edu |
    | home : http://www.graphics.lc s.mit.edu/~decoret|
    +-------------------------------------------------+

  • Jerry Coffin

    #2
    Re: Overloading a "library&q uot;

    In article <bdpgd1$2en3$1@ grapevine.lcs.m it.edu>,
    decoret@graphic s.lcs.mit.edu says...

    [ ... ]
    [color=blue]
    > 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.[/color]

    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.

    --
    Later,
    Jerry.

    The universe is a figment of its own imagination.

    Comment

    Working...