Search code examples
c++embeddedgoogletest

Handling duplicate symbols for peripheral registers when testing embedded C++ code using googletest


I'm developing a hobby project for MSP430F5529 using C++ and testing using googletest. I'm a true beginner both at C/C++, microcontrollers/embedded and googletest.

The peripherals on the MSP are controlled via registers and TI provides a header <msp430.h> that includes a processor specific header, msp5529.h, in my case and that header defines a large number of constants for bits etc but it also declares the registers available on the microcontroller for example UCA1CTL1used to setup serial communication.

When I compile for build <msp430.h> is included in UART.h for example and everything works as intended. When testing however I want to include a testable version of <msp430.h> which we can call testable_msp430.h.

So basically we have the following:

UART.h

#ifndef TESTING
#include <msp430.h>
#else 
#include "testable_msp430.h"
#endif

testable_msp430.h

int UCA1CTL1;

*A bunch of other declarations*

test_UART.cpp

#include UART.h

*A bunch of tests*

UART.cpp

#include UART.h

*A bunch of source*

The problem is that when compiling this for test by running g++ -std=c++11 src/UART.cpp test/test_UART.cpp -lgtest -lgtest_main -pthread -o testOutput -DTESTING I get a link error stating

duplicate symbol _UCA1CTL1 in:
    /var/folders/yr/mkwg3mhs1nl93l35x6t55vz80000gn/T/UART-772fab.o
    /var/folders/yr/mkwg3mhs1nl93l35x6t55vz80000gn/T/test_UART-2e1a90.o

which makes sense since UCA1CTL1is defined in both the compilation unit for UART.cppand test_UART.cpp. My question is therefore how memory mapped registers are usually handled to be able to test against/using them?

Thanks in advance!


Solution

  • You have definitions rather then declarations in testable_msp430.h. Rather than:

    int UCA1CTL1;
    

    you should have:

    extern int UCA1CTL1;
    

    Then in another translation unit linked only to the test or wrapped in #ifndef TESTING, or within test_UART.cpp, you place the single test definition of UCA1CTL1 et al.