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[edit]
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.
- #ifndef __WORKAROUND_BE64TOH_H
- #define __WORKAROUND_BE64TOH_H
- #include <stdint.h>
- #ifdef HAVE_BE64TOH
- #include <endian.h>
- #else
- uint64_t be64toh(uint64_t val) __attribute__((weakref("_int_be64toh")));
- #endif /* HAVE_BE64TOH */
- #endif /* __WORKAROUND_BE64TOH_H */
- #ifdef HAVE_CONFIG_H
- #include "config.h"
- #endif /* HAVE_CONFIG_H */
- #include "be64toh.h"
- #include <arpa/inet.h>
- 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[edit]
(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[edit]
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.)