Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to conditional compile main() in C?

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.

like image 382
CisBae Avatar asked Mar 16 '23 09:03

CisBae


2 Answers

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.

like image 175
wolfPack88 Avatar answered Mar 23 '23 11:03

wolfPack88


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.

like image 23
Arman Hatefi Avatar answered Mar 23 '23 10:03

Arman Hatefi