I'm trying to wrap a library function with the GCC linker option -wrap. As far as I've read up, this should replace the symbol libfoo with __wrap_libfoo and give access to the original definition by __real_libfoo.
I've implemented it like this:
original.h
#ifndef ORIGINAL_H
#define ORIGINAL_H
void libfoo();
#endif //ORIGINAL_H
original.cpp
#include "original.h"
#include <iostream>
void libfoo()
{
std::cout<<"Original libfoo called from original.cpp"<<std::endl;
return;
};
And compiled to a static lib with g++ --std=c++11 -c original.cpp -o liboriginal.o
, packed up with ar rcs liboriginal.a liboriginal.o
and moved to a location known to the linker.
wrapper.h
#ifndef WRAPPER_H
#define WRAPPER_H
// should not need anything here
#endif //WRAPPER_H
wrapper.cpp
#include "wrapper.h"
#include <iostream>
//forward declaration to suppress compiler error
void __real_libfoo();
void __wrap_libfoo()
{
std::cout<<"Wrapper libfoo called from wrapper.cpp"<<std::endl;
__real_libfoo();
return;
};
Compiled again to a static lib with g++ --std=c++11 -c wrapper.cpp -o libwrapper.o
, packed up with ar rcs libwrapper.a libwrapper.o
.
main.cpp
#include "original.h"
int main()
{
libfoo();
return 0;
}
Compiled with g++ --std=c++11 -c main.cpp -o main.o
and linked everything together with g++ -L. -Wl,-wrap=libfoo -o test ./main.o -loriginal -lwrapper
On execution, I only get Original libfoo called from original.cpp at the console.
Why does the linker not replace the symbol so the call is redirected to __wrap_libfoo()
?
And, if this is solved, how do I handle multiple, overloaded functions, which all should be wrapped? Do I need just one -wrap=function_name
or do I need to somehow add a more detailed signature to the linker option?
Update: I've also tried not linking the wrapper as a lib, but as an object file instead. This gives me a undefined ref error from the linker regarding the missing __real_libfoo() implementation.