Search code examples
centry-point

Develop C with multiple main entry points


I used to develop Java project by Eclipse. A Java project can contain many code files with the main function (the entry point), so we can run each code file which has a main function.

But now I want to develop C project by Eclipse CDT. In a C project we can have only one main function. Can I have many code files with a main function and run each file just like I would in Java?

P.S.: I don't like to write Make Target for each file by main self


Solution

  • Javas option to have a main in every object is highly irritating and does not make sense to me.

    I assume you want to train a bit in c and want to find a way to have all training lessons in one file. Here is an option that would do that for you in a crude way. This would not be reasonable to do as an application but you can use this to execute different options.

    To use this you would call your program like 'progname 1'.

    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    int ProgrammingLesson001(void);
    
    
    int main(int argc, char * argv[])
    {
        int i;
        int option;
        int e = 0;
    
        printf("%i\n", argc);
    
        for(i = 0; i < argc; ++i)
        {
            printf("%s\n", argv[i]);
        }
    
        if(2 == argc)
        {
            option = atoi(argv[1]);
            printf("Your Option was '%s' interpreted as %i\n", argv[1], option);
        }
        else
        {
            option = 0;
            e |= 1;
        }
    
        switch(option)
        {
        case 0:
            printf("zero is an error\n");
            e |= 1;
            break;
        case 1:
            e |= ProgrammingLesson001();
            break;
        default:
            break;
        }
    
        if(0 != e)
        {
            printf("an error has occureed\n");
        }
    
        return e;
    }
    
    int ProgrammingLesson001(void)
    {
        printf("This could behave like a main for training purposes\n");
    }
    

    If you spent some time programming in c take a second look at makefiles. You can create a makefile that will fit all your programs. This reduces the actual work you need to put into this so much that maintaining the switch construct is harder than creating a new project.