write a c program which contains two main function and inform to the pre-processor to consider only one main function

28 Dec 2022 Balmiki Mandal 0 C Programming

Writing a C Program with Two Main Functions: How to Specify Which One to Use

In C programming language, it is not possible to have two main functions in a single program. However, you can use conditional compilation directives to inform the pre-processor to consider only one of the main functions. Here's an example program:

#include <stdio.h>

#define MAIN_ONE  // Define this macro to use the first main function

int main() {
#ifdef MAIN_ONE
    printf("This is the first main function.\n");
#else
    printf("This is the second main function.\n");
#endif
    return 0;
}

#ifdef MAIN_TWO
int main() {
    printf("This is the second main function.\n");
    return 0;
}
#endif

In the above program, there are two main functions, but only one will be compiled and executed depending on the pre-processor directive. The MAIN_ONE macro is defined before the first main function, so the first main function will be considered for compilation. If you want to use the second main function instead, you can define the MAIN_TWO macro instead. Note that only one of the macros can be defined at a time, and the other one must be commented out.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.