2011-07-08 19 views
2

我不知道爲什麼我不能鏈接這個程序。首先這是我的頭文件,gcd.h:簡單的C++程序不能鏈接到Windows下的MingW

#ifndef GCD_H 
#define GCD_H 

/** 
* Calculate the greatest common divisor of two integers. 
* Note: gcd(0,0) will return 0 and print an error message. 
* @param a the first integer 
* @param b the second integer 
* @return the greatest common divisor of a and b 
*/ 

long gcd(long a, long b); 

#endif 

這是我gcd.cpp文件:

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

long gcd(long a, long b) { 

    // if a and b are both zero, print an error and return 0 
    if ((a==0) && (b==0)) { 
     cerr << "WARNING: gcd called with both arguments equal to zero." << endl; 
     return 0; 
    } 

    // Make sure a and b are both nonnegative 
    if (a<0) { 
     a = -a; 
    } 
    if (b<0) { 
     b = -b; 
    } 

    // if a is zero, the answer is b 
    if (a==0) { 
     return b; 
    } 

    // otherwise, we check all the possibilities from 1 to a 
    long d; // d will hold the answer 

    for (long t=1; t<=a; t++) { 
     if ((a%t==0) && (b&t==0)) { 
      d = t; 
     } 
    } 

    return d; 
} 

的主要問題是,當我編譯,則返回錯誤

c:/ mingw/bin /../ lib/gcc/mingw32/4.5.2 /../../../ libmingw32.a(main.o):main.c :(.text + 0xd2 ): 未定義引用'WinMain @ 16'collect2:ld返回1退出 狀態

我不明白這是什麼意思。

請幫忙?

好吧其實可以有人只是修改我的代碼,以便它正常運行?這是目前最好的選擇,因爲那樣我纔會明白我做錯了什麼。

+0

你使用什麼編譯器?我猜gcc是因爲包含在錯誤信息中的路徑 –

+0

他/她正在使用GCC。你可以在他們的路上看到它。 – kmdent

+0

與問題無關:有很多更有效的GCD實施方式,您應該嘗試Google以獲得更好的解決方案。 –

回答

5

你的main函數(程序的入口點)在哪裏?

順便說一句,我喜歡你寫的「主要問題」 :)

+0

它看起來像它期望一個winmain函數以及..可能它正在編譯爲winapi或類似的東西.. –

+0

不,這就是cygwin gcc打印出來的內容: –

+0

C:\ Users \ Yannik \ AppData \ Local \ Temp \ ccLumP2t。 o:testing.cpp :(。text + 0x71):未定義引用'gcd(long,long)' collect2:ld返回1退出狀態是編譯器錯誤,當我這樣做時... – Glassjawed

0

這是不是一個程序,它是一個單一的功能。

它可以獨立編譯,但無法鏈接到可執行文件,因爲它沒有入口點。鏈接器抱怨缺少入口點(根據編譯器啓動代碼的預期名稱)。

+0

如何獨立編譯?當我試圖這樣做時,它給了一個錯誤。 另外我試過鏈接,並沒有工作。 – Glassjawed

+0

'#include「gcd.h」 #include using namespace std; /** *測試gcd程序的程序。 */ int main(){ \t long a,b; \t cout <<「輸入第一個數字 - >」; \t cin >> a; \t cout <<「輸入第二個數字--->」; \t cin >> b; << a <<「和」<< b <<「的gcd是」 \t \t << gcd(a,b)<< endl; \t return 0; }' – Glassjawed

+0

(包含調用gcd函數的頭文件) – Glassjawed

0

你是如何編譯你的代碼的?它應該是這樣的:

g++ gcd.cpp -o gcd 

不要#include <windows.h>或添加-mwindows到您的命令。

+0

我不包括-mwindows。我再次獲得了對WinMain錯誤的未定義引用。 如果我包括-mwindows,我該如何刪除-mwindows?我正在使用EditPlus,並沒有明確地說#include 或任何東西。 – Glassjawed