Unittest replacement function in library

Suppose that you need to implement a replacement function, for instance be64toh which was added in glibc-2.9, to remain compatible with legacy system. Ofcourse you want to use the real function if available.

Function implementation
The replacement is called _int_be64toh and the header conditionally aliases be64toh to _int_be64toh. This way it is possible to compile on any system without any interference. It might be a good idea to adjust the visibility of the function as well.


 * 1) ifndef __WORKAROUND_BE64TOH_H
 * 2) define __WORKAROUND_BE64TOH_H


 * 1) include 


 * 1) ifdef HAVE_BE64TOH
 * 2) include 
 * 3) else

uint64_t be64toh(uint64_t val) __attribute__((weakref("_int_be64toh")));


 * 1) endif /* HAVE_BE64TOH */


 * 1) endif /* __WORKAROUND_BE64TOH_H */


 * 1) ifdef HAVE_CONFIG_H
 * 2) include "config.h"
 * 3) endif /* HAVE_CONFIG_H */


 * 1) include "be64toh.h"
 * 2) include 

union bits { uint32_t v[2]; uint64_t d; };

uint64_t _int_be64toh(uint64_t big_endian_64bits){ union bits out, in = { .d = big_endian_64bits };

out.v[1] = ntohl(in.v[0]); out.v[0] = ntohl(in.v[1]);

return out.d; }

Conditional compilation
(Not showing the configure test, it varies too much depending on context)

 if BUILD_BE64TOH libfoo_la_SOURCES += be64toh.c be64toh.h endif

tests_bar_CFLAGS = ${AM_CFLAGS} -Dfulhack tests_bar_LDADD = libfoo.la tests_bar_SOURCES = tests/bar.c be64toh.c

-Dfulhack (or anything similar) is needed or you get Makefile.am: object `be64toh.$(OBJEXT)' created both with libtool and without

Unittest
Now you can use _int_be64toh in you unittests (if you want to compare the result with the system implementation, which is a good idea, you can only run the test if HAVE_BE64TOH is defined.)