M W
M W

Reputation: 67

c++ can't compile a file

I'm a beginner at c++ and I'm trying to write a program to find greatest common factor. In main i have:

#include <iostream>
#include <cstdlib>
#include "longgcd.cpp"
int main(int argc, char* argv[]){
  long gcd(long m, long n);
  long m,n,g;
  m=atol(argv[1]);
  n=atol(argv[2]);
  g=gcd(m,n);
  std::cout<<"gcd("<<m<<","<<n<<")="<<g<<std::endl;
  return 0;
}

and then i put the subfunction into another file called longgcd.cpp

#include <iostream>
#include <cstdlib>
long gcd( long m, long n){
  long r;
  while(n !=0){
    r=m%n;
    m=n;
    n=r;
  }
  return m;
}

somehow longgcd.cpp can't compile. i get an error:

/usr/lib/gcc/i486-linux-gnu/4.3.2/../../../../lib/crt1.o: In function `_start':
(.text+0x18): undefined reference to `main'
collect2: ld returned 1 exit status
make: *** [longgcd] Error 1

somehow I have difficulty running this program and making it work, i can't see whats wrong with it. Thanks for any help or suggestions.

Upvotes: 0

Views: 5713

Answers (4)

Tony The Lion
Tony The Lion

Reputation: 63190

One issue is that main should be in your .cpp file, and not your header.

Another is that you normally #include a header (.h or .hpp) into a .cpp file and not the other way around.

Also please get a decent C++ book to read.

Upvotes: 1

Bob Fincheimer
Bob Fincheimer

Reputation: 18036

Do not include longgcd.cpp. You should almost never include a .cpp (unless you really, really, know what is going down)

You should specify all the cpps to the compiler. E.g: g++ main.cpp longgcd.cpp

Also move the long gcd(long m, long n); line above your main function.

Upvotes: 0

Alexander Gessler
Alexander Gessler

Reputation: 46607

You should be compiling the source file that contains the main() function.

Note that #includeing cpp's is generally discouraged. You can put the declaration for gcd in a header file and include this file from both the implementation cpp containing the code for it and the main file that calls it. In this case you will need to specify both cpp files to the compiler command line because they're both needed to assemble the final program. Even with this complication this way is much better than including cpps.

Upvotes: 1

Lily Ballard
Lily Ballard

Reputation: 185653

Can you show the line you used to compile? It sounds like you tried to compile longgcd.cpp independently as an executable, and since that file doesn't have main, the linker correctly complained that it couldn't find main.

The simplest solution is to compile both files together

g++ $FLAGS longgcd.cpp main.cpp

Upvotes: 1

Related Questions