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.
Haven't you try the use of pre-processor compiler conditions? May be you've tried but it doesn't work, hum?
Anyway, you probably should:
1- Define a token at top of "tests.c" class file like:
#defined foo_MIN_UNIT_TEST
2- Surround your "main() { ... } " method in "foo.c" class file with #ifndef / #endif like:
#ifndef foo_MIN_UNIT_TEST //consider using #ifndef not #ifdef!!!
int main()
{ ... }
#endif
3- This way, when you compile your unit test files, the main() method of foo.c will not be included in compile time and the only main() method of tests will be available to compiler.
For further reading: http://www.cprogramming.com/
Regards.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With