Compile-time error: multiple definition of 'main'

I get the following error: multiple definition of `main '

I created a new project, it has two C ++ files:

File 1

#include <iostream> using namespace std; int main() { cout<<"Hello World"; //fflush(stdin); //getchar(); return 0; } 

File 2

 #include <iostream> using namespace std; int main() { cout<<"Demo Program"; return 0; } 

When I click on the Build project and Run, I get an error. How to run these files?

+7
source share
4 answers

You cannot have two main functions in one project. Put them in separate projects or rename one of the functions and call it from another main function.

You can never have more than one main () function in your project, since it is an entry point, regardless of what the list of parameters is.

However, you may have several declarations of other functions if the parameter list is different ( function overload ).

File 1

 #include <iostream> using namespace std; int main() { cout<<"Hello World"; otherFunction(); return 0; } 

File 2

 #include <iostream> using namespace std; void otherFunction() { cout<<"Demo Program"; } 

Don't forget about the appropriate #includes.

+11
source

You cannot have two main functions. In fact, you cannot have two functions that have the same signature through your project (and not your files).
And since Mr. TAMER said that the core is a special case, you cannot even have two functions called main .

+4
source
  • Determine which file you want to be the entry point to the project.

  • In another file, change the method name to a different name. You can call it from the file that you selected in step 1.

main is the entry point of your program, and you cannot have more than one entry point.

For a clearer explanation, see this: Two "core" functions in C / C ++

+1
source

You cannot use the same function signature in the same project, because the compiler starts execution from main (). If you define main () several times, then an error occurs.

file1.c

 #include <iostream> #include <file2.h> using namespace std; int main() { cout<<"Hello World"; //fflush(stdin); //getchar(); return 0; } 

And in file2.h you can define the function file2.c (first rename main () of file2)

0
source

All Articles