Building differently depending on whether a library or a program

07 May 2015

I would like to include in my libraries a sample test main(). If the library is imported as a program and compiled, then the main() would get built and linked, and generates some test output. If the library is used normally, the main() is not built into the code, preventing linker errors.

are there any predefine preprocessor directives that I could look at to make this determination? If not, does anyone have a suggestion on how I might implement a test routine into my library?

For clarity, here is a simple example:

Here is a link to the library/program if you want to experiment/pull request suggestions

Import libraryExampleLibrary_Program

An example of a cpp file that I want to compile differently depending whether it is a program or a library.

example code that wants to know if it is a program or a library

#include "mbed.h"

class LED_TEST:public DigitalOut{
   public:
   LED_TEST(PinName pin):DigitalOut(pin) {};

   void TurnOn() {write(1);}
   void TurnOff() {write(0);}
};

#ifdef __IN_A_PROGRAM   //if I'm compiling as a program then I want to create this main for testing.
                        //if I'm compiling as a library I do not want the main to prevent linker problems
int main(void)
{
LED_TEST lt(LED1);
    while (1)
    {
        lt.TurnOn();
        wait(1);
        lt.TurnOff();
        wait(1);
    }
}
#endif