Unittest replacement function in library

From Sidvind
Jump to: navigation, search

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.

Code: be64toh.h (view, download)

  1. #ifndef __WORKAROUND_BE64TOH_H
  2. #define __WORKAROUND_BE64TOH_H
  3.  
  4. #include <stdint.h>
  5.  
  6. #ifdef HAVE_BE64TOH
  7. #include <endian.h>
  8. #else
  9.  
  10. uint64_t be64toh(uint64_t val) __attribute__((weakref("_int_be64toh")));
  11.  
  12. #endif /* HAVE_BE64TOH */
  13.  
  14. #endif /* __WORKAROUND_BE64TOH_H */

Code: be64toh.c (view, download)

  1. #ifdef HAVE_CONFIG_H
  2. #include "config.h"
  3. #endif /* HAVE_CONFIG_H */
  4.  
  5. #include "be64toh.h"
  6. #include <arpa/inet.h>
  7.  
  8. union bits {
  9.         uint32_t v[2];
  10.         uint64_t d;
  11. };
  12.  
  13. uint64_t _int_be64toh(uint64_t big_endian_64bits){
  14.         union bits out, in = { .d = big_endian_64bits };
  15.  
  16.         out.v[1] = ntohl(in.v[0]);
  17.         out.v[0] = ntohl(in.v[1]);
  18.  
  19.         return out.d;
  20. }

Conditional compilation[edit]

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

Code: Makefile.am (view, download)

  1. if BUILD_BE64TOH
  2. libfoo_la_SOURCES += be64toh.c be64toh.h
  3. endif
  4.  
  5. tests_bar_CFLAGS = ${AM_CFLAGS} -Dfulhack
  6. tests_bar_LDADD = libfoo.la
  7. 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.)