multiple definition of main first defined here

2019-03-04 15:34发布

问题:

I'm new to programming and currently I'm learning C programming. I'm writing codes on the code blocks and in it using GCC compiler. When I create a new project, (as you know it creates main.c file with it) and due to that I'm not able to compile another file in that project.

File 1:

 #include<stdio.h>

int main()
{
    int a,b,c,d;
    printf("Enter three numbers\n");
    scanf("%d%d%d",&a,&b,&c);
    d=a;
    if(b>d)
        d=b;
    if(c>d)
        d=c;
    printf("\n The maximum of three numbers is %d",d);

}

File 2: main.c

#include <stdio.h>

int main()
{
    printf("Hello world!\n");
    return 0;
}

When I compile the first programme, it shows the following error: multiple definition of 'main' first defined here

I've searched every where I could and I'm not able to solve this. In one of the answers here on stack overflow, someone had suggested to write this in (Project->Build options...->Linker settings (tab))

-Wl,--allow-multiple-definition

When I wrote it, there were no errors. But it wasn't able to run my File 1 and instead, it runs that main.c file. Even when I close the main.c file, it opens there again and runs main.c file which gives the output "Hello World!".

Initially when I was using code blocks there were no such errors. I don't know why this is happening and I've not much knowledge about compilers.

回答1:

As noted in comments you can only have one main function.

So when you start a new project you need to replace the main.c file with the main.c file you want to use. Or you can edit the 'hello world' main.c program.

When you start a new project in code::blocks you can get a new directory with a simple program that prints 'Hello World'. This file is usually main.c. You need to edit this file or replace it. The reason that code::blocks puts this simple main.c program in the new project is so that you can compile it and test your system without having to write a new program.



回答2:

Some computer languages allow you to use the same function name for different functions ( which are identified by their parameters and sometimes return types ). That's called overloading. C does not allow this. Functions in C must have unique names.

The main() function is a special one in C as it is used as the standard entry point for applications. That is, the main() function will be called first and your application should start and (typically) end in that function.

As a beginner I would suggest you avoid automated editor features that create and build projects for you. You will miss out on learning how things work doing that. Use an editor to start from empty files and learn how they all connect and how to use the compiler from the command line. The command line is something every beginner should start from, IMO.

It may be harder to learn, but it will give you a much better feel for what is going on.