2013-03-04 71 views
3

我正在從Edward Schneinerman的C++學習C++的數學家。我工作的最大公約數部分第2章中我取得了三個文件:編譯一個C++程序頭文件(新手)

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); 
} 

和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; 
} 

所有這些文件駐留在相同的目錄中。當我嘗試編譯gcdtest.cc

$ g++ -Wall gcdtest.cc -o gcdtest.exe 

我收到以下錯誤:

$ 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 

我全新的C++和還沒有完全grokked編譯和鏈接。我究竟做錯了什麼?

+1

您還沒有編譯你的gcd.cc文件,因此聯動尋找最大公約數時失敗函數 – SomeWittyUsername 2013-03-04 15:24:19

+0

另外,你在'gcd.cc'中有一個輸入錯誤。 'retrun!= return' – MikeTheLiar 2013-03-04 15:42:29

回答

5

你應該嘗試編譯兩個C文件:

$ g++ -Wall gcdtest.cc gcd.cc -o gcdtest.exe 

否則你有「最大公約數」聲明(在頭文件),但是編譯器丟失其實施。

0

您必須先編譯gcd.cc。

$g++ -c gcd.cc -o gcd.o 
$g++ gcdtest.cc gcd.o -o gcdtest.exe 
+1

你的第一條線是不正確的。這將嘗試創建一個名爲gcd.o的二進制文件,並且會因缺少主文件而失敗。 – 2013-03-04 15:25:18

+0

謝謝謝爾斯,你說得對。 – 2013-03-04 15:42:06

2

編譯程序或者是這樣的:

g++ -Wall gcd.cc gcdtest.cc -o gcdtest.exe 

或者這樣說:

g++ -Wall -c gcdtest.cc 
g++ -Wall -c gcd.cc 
g++ -Wall gcd.o gcdtest.o -o gcdtest.exe