我正在从Edward Schneinerman的数学家C ++学习C ++。我正在研究第2章中最大的公约数部分。我已经制作了三个文件:
gcd.h
#ifndef GCD_H
#define GCD_H
long gcd(long a, long b);
#endif
gcd.cc
#include "gcd.h"
#include<iostream>
using namespace std;
long gcd(long a, long b) {
if( a == 0 && b == 0 ) {
cerr << "WARNING: gcd(0,0) not defined" << endl;
return 0;
}
if( a < 0 ) a = -a;
if( b < 0 ) b = -b;
if( b == 0 ) retrun a;
if( a == 0 ) return b;
long c = a % b;
return gcd(b,c);
}
和gcdtest.cc
#include "gcd.h"
#include <iostream>
using namespace std;
int main() {
long a,b;
cout << "Enter the first number > ";
cin >> a;
cout << "Enter the second number > ";
cin >> b;
long d = gcd(a,b);
cout << "The gcd of " << a << " and " << b << " is " << d << endl;
return 0;
}
所有这些文件都位于同一目录中。当我尝试编译gcdtest.cc
时$ g++ -Wall gcdtest.cc -o gcdtest.exe
我收到以下错误:
$ g++ -Wall gcdtest.cc -o gcdtest.exe
Undefined symbols for architecture x86_64:
"gcd(long, long)", referenced from:
_main in ccgbCyQO.o
ld: symbol(s) not found for architecture x86_64
collect2: ld returned 1 exit status
我是C ++的新手,并没有完全搞定编译和链接。我做错了什么?
答案 0 :(得分:5)
您应该尝试编译两个C文件:
$ g++ -Wall gcdtest.cc gcd.cc -o gcdtest.exe
否则你声明了'gcd'(在头文件中),但是编译器缺少它的实现。
答案 1 :(得分:2)
以这种方式编译程序:
g++ -Wall gcd.cc gcdtest.cc -o gcdtest.exe
或者这样:
g++ -Wall -c gcdtest.cc
g++ -Wall -c gcd.cc
g++ -Wall gcd.o gcdtest.o -o gcdtest.exe
答案 2 :(得分:0)
你必须先编译gcd.cc。
$g++ -c gcd.cc -o gcd.o
$g++ gcdtest.cc gcd.o -o gcdtest.exe