Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Help with learning how to compile small project (3 files)

Status
Not open for further replies.

jmvbxx

Programmer
Dec 18, 2008
2
I am a brand new coder learning from C++ for Mathematicians. I have three files: gcd.h, gcd.cpp and gcd-tester.cpp

What I'd like to know if how to compile them so that I can run them.

I believe that gcd-tester.cpp needs gcp.cpp in order to compile.

Here is the error I receive:

~/coding/cpp/gcd$ g++ gcd-tester.cc -o gcd-tester
/tmp/ccvi6bre.o: In function `main':
gcd-tester.cc:(.text+0xcc): undefined reference to `gcd(long, long)'
collect2: ld returned 1 exit status

Any help is very appreciated!

Here is the code for gcd-tester.cpp

Code:
   #include "gcd.h"
   #include <iostream>
   using namespace std;

   /**
     * A program to test the gcd procedure.
     */

   int main() {

      long a,b;

      cout << "Enter the first number --> ";
      cin >> a;
      cout << "Enter the second number --> ";
      cin >> b;

      cout << "The gcd of " << a << " and " << b << " is "
           << gcd(a,b) << endl;
      return 0;
   }
 
For a simple project, you can get away with listing both source files on the command line:
Code:
$ g++ gcd.cpp gcd-tester.cpp -o gcd-tester

However, the correct way (especially on larger projects) is to compile each source file into an object file (ending with[tt] .o[/tt]) using the[tt] -c [/tt]option, then link the object files together:
Code:
$ g++ -c gcd.cpp
$ g++ -c gcd-tester.cpp
$ g++ gcd.o gcd-tester.o -o gcd-tester

You may also want to look into creating a Makefile do perform these steps for you.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top