我是C ++编码的新手,并且正在尝试自学课堂。 我需要创建一个菜单驱动的程序,它将执行两个函数,一个用于查看字符串是否为回文,另一个用于查看找到两个数字的最大公分母。
我有一个main.cpp,一个GCD.cpp,一个palindrome.cpp,一个GCD.h和一个palindrome.h。当我在命令行上编译时,我收到以下错误:
/tmp/ccVf007n.o:在函数'main'中:main.cpp :(。test + 0x75):对euclid(int,int)的未定义引用; collect2:错误:ld返回1退出状态。
我的代码块是: main.cpp中
#include <iostream>
#include "palindrome.h"
#include "GCD.h"
#include <string>
using namespace std;
void showChoices();
int x,y;
int main() {
int choice;
do
{
showChoices();
cin >> choice;
switch (choice)
{
case 1:
cout << "Palindrome Program.";
main();
break;
case 2:
cout << "Greatest Common Denominator Program.";
euclid(x,y);
break;
case 3:
break;
}
}while (choice !=3 );
}
void showChoices(){
cout << "Menu" << endl;
cout << "1. Palindrome Program" << endl;
cout << "2. Greatest Common Denominator Program" << endl;
cout << "3. Exit" << endl;
}
GCD.cpp
#include <iostream>
using namespace std;
int euclid (int*, int*);
int main() {
int a, b;
cout << "A program to find GCD of two given numbers.";
cout << "\n\nEnter your choice of a number: ";
cin >> a;
cout << "\nEnter your choice of another number: ";
cin >> b;
cout << "\n\nProcessing with Euclid method";
cout << "\nThe GCD of " << a << " and " << b << " is " << euclid(a, b);
return 0;
}
int euclid ( int *x, int *y) {
if ( x % y == 0 )
reutrn y;
else return euclid ( y, x%y );
}
palindrome.cpp
#include<iostream>
using namespace std;
int main(){
char string1[20];
int i, length;
int flag = 0;
cout << "Enter a string: ";
cin >> string1;
length = strlen(string1);
for(i=0;i < length ;i++){
if(string1[i] != string1[length-i-1]){
flag = 1;
break;
}
}
if (flag) {
cout << string1 << " is not a palindrome" << endl;
}
else {
cout << string1 << " is a palindrome" << endl;
}
system("pause");
return 0;
}
GCD.h
#ifndef PROJ4_GCD_H
#define PROJ4_GCD_H
int euclid (int, int);
#endif //PROJ4_GCD_H
palindrome.h
#ifndef PROJ4_PALINDROME_H
#define PROJ4_PALINDROME_H
char string1[20];
int i, length;
int flag = 0;
#endif //PROJ4_PALINDROME_H
我感谢所有的投入和帮助。谢谢,
答案 0 :(得分:1)
在标题中定义
int euclid (int, int);
但在您实施的.cpp
文件中
int euclid (int*, int*);
因此,当您将其作为gcd(a, b)
调用时,链接器将无法找到整数版本。摆脱指针。
PS:在您调用main()
的交换机中,您需要拨打palindrome()
:
switch (choice)
{
case 1:
cout << "Palindrome Program.";
// main();
palindrome();