-3

While doing programming in Code::Blocks it does not compile for C++. Even for a this kind of a simple program.

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

it gives those errors.

=== Build: Debug in start (compiler: GNU GCC Compiler) ===

obj\Debug\start.o||In function `main':
C:\Users\dp\Desktop\c++\start\start.cpp|4|multiple definition of `main'
obj\Debug\main.o:C:\Users\dp\Desktop\c++\start\main.cpp|6|first defined here
error: ld returned 1 exit status
=== Build failed: 3 error(s), 0 warning(s) (0 minute(s), 6 second(s)) ===

what can i do to fix this.

  • 1
    [`using namespace std;` is a bad practice](https://stackoverflow.com/q/1452721/2176813), never use it. – tambre Dec 02 '17 at 12:46
  • 1
    Unable to reproduce. Judging by your command line you seem to be linking together multiple object files, of which each contain a separate `main` function (thus multiple definition). – tambre Dec 02 '17 at 12:47
  • @tambre how ever the there is no syntax error. so this sode must run and show the out put. but it doesn't. how can i fix this – P.M sandaru Chathuranga Dec 02 '17 at 12:49
  • Having no syntax error doesn't mean that your code must be able to link without problems. The fix is basically stated by my comment - don't link together multiple objects with the same definitions. – tambre Dec 02 '17 at 12:52
  • @tambre but this code runs in other computers. does not run in mine. i reinstall the code blocks. but the errors are same. – P.M sandaru Chathuranga Dec 02 '17 at 12:56
  • Presumably because on other computers you aren't linking with another object file. Please provide your command line for invoking the compiler. – tambre Dec 02 '17 at 12:58
  • 2
    You need to provide a [mcve] – Passer By Dec 02 '17 at 13:01
  • 3
    The message states that you have one file `start.cpp` and one file `main.cpp`, **both** containing a `main` function. So it doesn't know where the program is to start. Now think about how you could resolve this. – Bo Persson Dec 02 '17 at 13:21

1 Answers1

2

As-is the code itself should compile fine. But as the error suggests you have multiple int main() function definitions across multiple source files. One is in the start.cpp and the other is in the main.cpp file. Either keep only one main() entry point or compile a single file. Compile with g++ front-end, not with gcc.

Ron
  • 14,674
  • 4
  • 34
  • 47