3

How to undef a library function to use my version of same function. Notice that I need to include the header file for other functions of same file. So not including is it not an option. Is there any way to use it without changing the name?

Yu Hao
  • 115,525
  • 42
  • 225
  • 281
Scroll-lock
  • 98
  • 1
  • 7

3 Answers3

5

You can do the following:

#define function_name function_name_orig
#include <library.h>
#undef function_name

int function_name() {
    /* ... */
}

This way the function will not be defined by the header, since it will be replaced by function_name_orig. Implementations of getters or setters in the header file may continue to work - even if they use function_name, since those calls will also be replaced.

urzeit
  • 2,755
  • 16
  • 35
  • 3
    There's a minor hazard that `` will do its own preprocessor magic to `function_name`. It might even define `function_name` to call some other function altogether. – sh1 Jul 12 '13 at 13:32
0

I just ran across this, and I couldn't do @urzeit's answer because it was std::sqrt. The compile error was ambiguity. But, extending @urseit's answer, I managed this solution:

// These fix occurrences of 'sqrt' on its own:
inline float stdSqrt(float val) { return ::std::sqrt(val); }
inline double stdSqrt(double val) { return ::std::sqrt(val); }
// These fix occurrences of scoped 'std::sqrt':
namespace std {
inline float stdSqrt(float val) { return ::std::sqrt(val); }
inline double stdSqrt(double val) { return ::std::sqrt(val); }
}
// Now we can apply urzeit's answer
#define sqrt(x) stdSqrt(x)r
#include "otherLibraryHeader.h"
#undef sqrt
Marupio
  • 123
  • 6
-3

For gcc, #undef seems to cut it, so long as you're keeping the same prototype for the function. For example:

#include <stdio.h>
#undef scanf

int scanf(const char * s, ...)
{
    printf(s);
    return 0;
}

int main()
{
    scanf("hello\n");
    return 0;
}

This compiles without warnings with -Wall, but if you want scanf to have a prototype of (say) void scanf(void) it will give errors.

Mjiig
  • 167
  • 5