Howto override #define directives in your C/C++ programs

This might be trivial for you experienced C/C++ programmers out there (and it really is), but…

Imagine the following scenario: you work on a project – say one that involves a microcontroller. On top, you have an add-on board (e.g.) based on a certain chip/IC that you wish to integrate in your design. You peek and poke over the Internet to find a ready-made library suitable for your add-on, but there’s none specific. However, you manage to find one that was built for a different add-on board that uses the same chip, except that the rest of the wiring on the PCB is ‘a bit’ different.

What do you do?

If you are sure you could use the same library (and why not if it’s the same chip/IC!?) – but not without any modifications specific to your particular add-on board, than the best approach would be to identify those pins from your add-on interfacing to your MCU board, and look them up in the header files of your chosen library – and do a #define directive override. This way, you keep the original library intact for future projects (possibly with the specific add-on board in mind!) and apply those changes specific to your current scenario.

Take this for example:

GSM3IO_H

This is the GSM3IO.h header file that comes with the Arduino GSM library. I didn’t have the Arduino GSM shield, yet I had a different board (with a GSM modem of course!) which was not purposely manufactured for use on an Arduino. So what!? It could still be done. Additionally, instead of an Uno, I was using a Mega ADK.

Later on I realized that this approach was not going to be that straight forward (despite my good intentions :)) so I looked and found an Arduino library specific for the GSM modem on my add-on board – where again, I would (have to) do a #define directive override.

It’s really simple.

This is without an override:

DefinesNoOverride

DefinesNoOverrideUART

This is with an override:

DefinesOverride

DefinesOverrideUART

Of course, the new defines have no practical meaning (1, 2 and 3!) but merely serve the example.

See that second #include directive?

And here is the contents of it:

#ifdef __RESETPIN__
#undef __RESETPIN__
#define __RESETPIN__ 1
#endif

#ifdef __TXPIN__
#undef __TXPIN__
#define __TXPIN__ 2
#endif

#ifdef __RXPIN__
#undef __RXPIN__
#define __RXPIN__ 3
#endif

First, check if your identifier is defined already. Second, if it is – you ‘un-define it’. Third, you ‘re-define it’.

Simple, right!?