2013-03-26 93 views
0

這可能以前曾被問過,但是,我發現它僅在類的上下文中,而事實並非如此。使用靜態庫鏈接時鏈接錯誤

Utils.h

#ifndef _UTILS_H_ 
#define _UTILS_H_ 

#include <cmath> 

//is 'x' prime? 
bool isPrime(long long int x); 

//find the number of divisors of 'x' (including 1 and x) 
int numOfDivisors(long long int x); 

#endif //_UTILS_H_ 

Utils.cpp

#include "Utils.h" 

bool isPrime(long long int x){ 
if (x < 2){ 
    return false; 
} 
long double rootOfX = sqrt(x); 
long long int flooredRoot = (long long int)floor (rootOfX); 

for (long long int i = 2; i <= flooredRoot; i++){ 
    if (x % i == 0){ 
     return false; 
    } 
} 

return true; 
} 


int numOfDivisors(long long int x){ 
if (x == 1){ 
    return 1; 
} 

long long int maxDivisor = (x/2) + 1; 
int divisorsCount = 0; 
for (long long int i = 2; i<=maxDivisor; i++){ 
    if (x % i == 0){ 
     divisorsCount++; 
    } 
} 

divisorsCount += 2; //for 1 & x itself 
return divisorsCount; 
} 

這兩個文件都在調試模式下編譯使用Visual Studio 2012作爲靜態庫。 現在我嘗試在一個單獨的項目中使用它們,我們將其稱爲MainProject:
1.將「Utils.vcproj」添加到MainProject解決方案。
2. MainProject依靠utils的
3.在「屬性」 - >「鏈接」 - >「輸入」 - >「附加依賴」把路徑Utils.lib

這裏是主哪個使用utils的:

#include <iostream> 
#include "..\Utils\Utils.h" 

using namespace std; 

int main(){ 


cout << "num of divisors of " << 28 << ": " << numOfDivisors(28) << endl; 

//this part is merely to stop visual studio and look at the output 
char x; 
cin >> x; 
return 0; 
} 

,這是錯誤我得到:

Error 1 error LNK2019: unresolved external symbol "int __cdecl numOfDivisors(__int64)" ([email protected]@[email protected]) referenced in function _main G:\ProjectEuler\Problem12\Source.obj Problem12 

爲什麼不能找到一個實現 「numOfDivisors」 的代碼?我已經給它包含它的.lib,此外 - 把對Utils項目本身的依賴... 任何幫助,將不勝感激。

+0

您的庫是以'C'還是'C++'編譯的? – SomeWittyUsername 2013-03-26 17:00:29

+0

我可以在哪裏查看? – BegemoD 2013-03-26 17:17:10

回答

0

看起來像方法numOfDivisors()沒有在你的Utils.cpp中定義,你可以檢查一次嗎?

爲什麼你的編譯器抱怨「G:\ ProjectEuler \ Problem12 \ Source.obj」? Source.obj從哪裏來?

您必須指定一個字段中的庫路徑和其他字段中的庫名稱,是否在適當的設置下指定了兩個字段?

+0

據我所知,我可以在「Properties」 - >「Linker」 - >「Input」 - >「Additional Dependencies」下指定.lib完整路徑。至少它在Visual2010中適用於我。 – BegemoD 2013-03-26 17:18:59

+0

我沒有意識到這一點 – 2013-03-26 17:44:10

0

假設庫的構建和鏈接正確,導致錯誤的下一個最可能的原因是該庫中的函數被命名爲其他內容,而不是鏈接到它的代碼中。

這可能是由影響名稱裝飾或類型名稱的任意數量的項目設置引起的。從遠處猜測你的案件中的罪魁禍首究竟是什麼?您可以比較兩個項目的屬性(手動或使用diff工具),並嘗試找出導致不同裝飾函數名稱的差異。