2013-03-26 96 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工具),并尝试找出导致不同装饰函数名称的差异。