Reputation: 8654
I am learning C++ from Edward Schneinerman's C++ for Mathematicians. I am working on the greatest common divisor section in chapter 2. I have made three files:
gcd.h
#ifndef GCD_H
#define GCD_H
long gcd(long a, long b);
#endif
gcd.cc
#include "gcd.h"
#include<iostream>
using namespace std;
long gcd(long a, long b) {
if( a == 0 && b == 0 ) {
cerr << "WARNING: gcd(0,0) not defined" << endl;
return 0;
}
if( a < 0 ) a = -a;
if( b < 0 ) b = -b;
if( b == 0 ) retrun a;
if( a == 0 ) return b;
long c = a % b;
return gcd(b,c);
}
and gcdtest.cc
#include "gcd.h"
#include <iostream>
using namespace std;
int main() {
long a,b;
cout << "Enter the first number > ";
cin >> a;
cout << "Enter the second number > ";
cin >> b;
long d = gcd(a,b);
cout << "The gcd of " << a << " and " << b << " is " << d << endl;
return 0;
}
All of these files reside in the same directory. When I attempt to compile gcdtest.cc
$ g++ -Wall gcdtest.cc -o gcdtest.exe
I receive the following error:
$ g++ -Wall gcdtest.cc -o gcdtest.exe
Undefined symbols for architecture x86_64:
"gcd(long, long)", referenced from:
_main in ccgbCyQO.o
ld: symbol(s) not found for architecture x86_64
collect2: ld returned 1 exit status
I am brand new to C++ and havent fully grokked compiling and linking. What am I doing wrong?
Upvotes: 3
Views: 980
Reputation: 17953
You have to compile gcd.cc first.
$g++ -c gcd.cc -o gcd.o
$g++ gcdtest.cc gcd.o -o gcdtest.exe
Upvotes: 0
Reputation: 81996
Compile your program either this way:
g++ -Wall gcd.cc gcdtest.cc -o gcdtest.exe
Or this way:
g++ -Wall -c gcdtest.cc
g++ -Wall -c gcd.cc
g++ -Wall gcd.o gcdtest.o -o gcdtest.exe
Upvotes: 2
Reputation: 35960
You should attempt to compile both C files:
$ g++ -Wall gcdtest.cc gcd.cc -o gcdtest.exe
Otherwise you have 'gcd' declared (in your header file), but compiler is missing its implementation.
Upvotes: 5