How can I have multiple definitions of main?

Viewed 145

In Java I can have a main function in every class and just use the one I want. This is often useful because I can put test routines in the main function run that class specifically to test it.

In C, however, no two functions can have the same prototype, so there can be only one main in the whole project. I can rename individual mains, but then I have to tediously edit the names to run the file of interest.

Is there any way around this, so I can have multiple mains, or is that just not going to happen?

2 Answers

Most of my C library code can be compiled with -DTEST to expose the main() (and often some auxilliary functions too) in the source file with the implementation. So if I have a set of functions declared in source.h and defined in source.c, then source.c might look like:

#include "source.h"
#include …other headers…

…code defining functions declared in source.h

#ifdef TEST

#include <stdio.h>

int main(void)
{
    …test code…
}

#endif /* TEST */

This works when the test suite is small enough to fit in the source file. If the tests get bigger than the code, then I create one or more separate source files containing test code. Each of those files can have its own main(), or they can be designed to be linked together — whichever seems more convenient.

What's appropriate depends on the size and complexity of the tests. Some functions end up with fixed — hard-wired — tests; some spend time reading data from standard input; others process argument lists if supplied and fall back on some minimal test if there are no arguments. The test code might use a unit test infrastructure or might be more or less ad hoc, again depending on complexity (and antiquity) of the code.

You can put the majority of your code into a shared library.

You would then have a source file with your "regular" main function that compiles to an executable by itself and uses the shared library. Then you can write a separate test program that also links in the library that can run the various tests needed.

Related