这个程序写在我们的书中,我们被告知要用C和C ++编译它,尽管它不适用于两者。下面的错误是当我尝试以.cpp格式编译它时
第一个错误:LNK2019:未解析的外部符号“long __cdecl oddnumber(短)”(?oddnumber @@ YAJF @ Z)在函数“int __cdecl evennumber(int)”中引用(?evennumber @@ YAHH @ Z) 第二个错误:LNK1120:1个未解析的外部
// This program shows function and variable declarations and their scopes.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
//#include<iostream.h>
int keven = 0, kodd = 0;
long evennumber(short);
long oddnumber(short);
int even(int);
int evennumber(int a) {
// genuine declaration
if (a == 2) {
printf("keven = %d, kodd = %d\n", keven, kodd);
return keven;
}
else {
a = (int) a / 2;
if (even(a)) {
// Is a even?
keven++;
return evennumber(a);
}
else {
kodd++;
return oddnumber(a);
}
}
// return a;
}
int oddnumber(int b) {
// genuine declaration
if (b == 1) {
printf("keven = %d, kodd = %d\n", keven, kodd);
return kodd;
}
else {
b = 3 * b + 1;
if (!even(b)){
//Isbodd?
kodd++;
return oddnumber(b);
}
else {
keven++;
return evennumber(b);
}
}
// return b;
}
int even(int x) {
// % is modulo operator.
return ((x % 2 == 0) ? 1 : 0);
}
void main() {
register short r = 0; // a register type variable is faster,
int i = r; // it is often used for loop variable
float f;
for (r = 0; r < 3; r++) {
printf("Please enter an integer number that is >= 2\n");
scanf("%d", &i);
if (even(i))
f = evennumber(i);
else
f = oddnumber(i);
}
}
答案 0 :(得分:1)
链接器指示您声明了符号long evennumber(short);
,但找不到该定义。首先检查函数的签名:声明和定义必须匹配!例如,我想你想申报int oddnumber(int)
?
如果要定义多个具有相同名称但签名不同的函数,请务必小心。这在C ++中是允许的,但在C中则不允许。