views:

47

answers:

1

So, I've got a library call init_foo(), and a function bar() that calls it. These live in library.o along with some other useful stuff that both need.

I want to write some code, bar_init_failure.t.c, to test what happens when init_foo() fails, without actually setting up the failure. In Perl, the bulk of our codebase, I'd launch Test::Resub and replace the library call with a stub that returns a failure code. To accomplish something similar in C, I was vaguely under the impression that I could redefine init_foo in the source for bar_init_failure.t.c and still link against library.o for the rest of the code, but gcc and ld complain about the duplicate symbols (instead of picking the first one) so I think I must be wrong about something (and I'm pretty rusty on this sort of stuff, so I'm not over-confident in my strategy).

Is there some way to appease the linker here, or is there another strategy that I should be using? (I'd prefer not to have to hack up the library.c code if I can help it.)

+1  A: 

If you can recompile library.c into a shared library, then you can redefine init_foo() within the unit tests. ld won't complain about duplicate symbols, neither at compile time, nor at execution`, and will invoke the function in the executable whatever the dynamic library contain - at least on Unix-like systems - I never tried on Windows.

This may prevent you from testing bar() as you won't be able to call the real init_foo() in the other tests ; unless you use dlsym() to invoke it from your own init_foo(), for instance when a global variable is set.

philippe