I have to write unit tests for functions of main.
I have, C:\sample\src\main.c
#include<stdio.h>
void main()
{
printf("\nthis is main file");
}
void print()
{
printf("\nthis is print function of main file");
}
C:\sample\src\main.h
#ifndef MAIN_H
#define MAIN_H
void print();
#endif
C:\sample\unitTest.c
#include<stdio.h>
#include<main.h>
void main()
{
printf("unit test");
print();
}
In the above programs, I want to trigger unit test from UnitTest.c file. I cannot have 2 main files in executable. How can I do this?
Normally your main function should probably be in a separate file from the rest of your code, as mentioned by other answerers.
But sometimes it IS better to keep your code all in one file. The situation I'm thinking of is when you're doing an assignment for school and you're supposed to submit just one .c file.
I have a solution for this case. The solution is to wrap the main function with an #ifndef like so:
main.c
#include <stdio.h>
void print()
{
printf("\nthis is print function of main file");
}
#ifndef DOING_UNIT_TESTS
void main()
{
printf("\nthis is main file");
}
#endif
And then define DOING_UNIT_TESTS before including your .c file in your test code, which cuts the main function out of the .c file as it is included:
testmain.c
#define DOING_UNIT_TESTS
#include "main.c" // yes, .c
void main()
{
// Do unit tests, or invoke a testing framework
}
The "correct" answer is to not put main() and print() in the same source (.c) file. From a code modularity perspective, the only things that should be in the same source file as main are helper functions for main that don't have a lot of meaning on their own - in other words, these things are not "units" and therefore you wouldn't want to unit test them, really. (This may be things like a function to parse command line arguments, or to output the help statement, for example.) If print() is a "unit" (or an entry point to a unit) then it should not be in the same source file as something that is not part of that unit (such as main()).
Since C is not object oriented, the language does not provide you with a natural way to group things that are logically connected. Therefore it's all the more important that you group things logically into source files such that each source file represents a "logical thing" (for some definition of "logical thing").
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