I'm working on a small open source project in C where I'm trying to use a test framework with C (the framework is min_unit
).
I have a foo.h
file with prototypes, and foo.c
, with the implementation.
In my test file, tests.c
, I have
#include "../test_framework/min_unit.h"
#include "foo.c"
... test cases ...
the problem is, because I have a main()
function in foo.c
(which I need to compile it), I can't compile tests.c
because I get an error that states
note: previous definition of ‘main’ was here
int main() {
My question is, is there a way to make it so that the main()
function in foo.c
is conditional, so that it does not compile when I'm running tests.c
? It's just annoying to have to remove and add main over and over.
The easiest way to use conditional compilation is to use #ifdef
statements. E.g., in foo.c
you have:
#ifdef NOT_TESTING //if a macro NOT_TESTING was defined
int main() {
//main function here
}
#endif
While in test.c
, you put:
#ifndef NOT_TESTING //if NOT_TESTING was NOT defined
int main() {
//main function here
}
#endif
When you want to compile the main
function in foo.c
, you simply add the option -DNOT_TESTING
to your compile command. If you want to compile the main
function in test.c
, don't add that option.