-3

I am really new to C++. I am trying to compile this simple program but I get an error

#include <iostream> 
int main(int argc, char** argv) 
{ 
   cout << "You have entered " << argc 
        << " arguments:" << "\n"; 
 
   for (int i = 0; i < argc; ++i) 
       cout << argv[i] << "\n"; 
 
   return 0; 
} 

The error that I get is

(.text+0x20): undefined reference to `main'
collect2: error: ld returned 1 exit status

I try to compile it as g++ file1.cpp I also tried g++ -c file1.cpp and then g++ main.exe file1.o which does not work as well. What am I doing wrong?

Alex
  • 63
  • 6
  • 2
    This error should not occur provided that you *really* have the `main` function in `file1.cpp`. If, for example, you named it `Main` for some reason, you will see exactly this error. Please double check the contents of your `file1.cpp` file. – Andreas Fester Dec 01 '20 at 14:47
  • 1
    The selected answer is considered bad practice, and shouldn't even be capable of fixing your issue. There is missing information here. I would have expected a different error for the code you're showing. – sweenish Dec 01 '20 at 15:03
  • instead of using using namespace std; at the start I added std whenever it was needed. For example std::cout – Alex Dec 01 '20 at 15:17
  • 2
    I believe the whole question should be deleted. I think the reason for the link error is somehow lost in changes to the code that happened after the error occurred. This code does have a compile error but that should not have given the link error. – drescherjm Dec 01 '20 at 15:48

2 Answers2

0

Maybe try and create a new file in an empty directory name it if you want something like main.cpp and put the code in that you needed for namespace and everything else and run

#include <iostream>
using namespace std;
    int main(int argc, char** argv) 
        { 
           cout << "You have entered " << argc 
                << " arguments:" << "\n"; 
         
           for (int i = 0; i < argc; ++i) 
               cout << argv[i] << "\n"; 
         
           return 0; 
        } 

It should work after and output a result Maybe check out this medium article for more about why you need using namespace std https://medium.com/breaktheloop/why-using-namespace-std-is-used-after-including-iostream-dc5ae45db652

-6

You can try specify namespace like this ->

#include <iostream>
using namespace std;

EDIT 'must' replaced by 'can try'. It works but why !

Florent
  • 436
  • 3
  • 8