C Primer對於分離式編譯的介紹很簡單,於是自己想試試看怎麼使用。按照以下程式碼執行,在main函數中執行fun()和absolute()時會提示沒有定義函數。請問這是為什麼?應該怎麼做才能讓程式碼順利運作?
主函數:
#include <iostream>
#include <string>
#include <vector>
#include "Chapter6.h"
using namespace std;
//cnt函数每次被调用则返回值+1
int cnt()
{
static int rtn = 0;
return rtn++;
}
int main()
{
for (size_t i = 0; i < 10; ++i)
{
cout << cnt() << endl;
}
int a = 0;
string c;
do
{
cout << "Please enter a number:" << endl;
cin >> a;
cout << a << "! = " << fun(a) << '\n' << absolute(a) << endl; //undefined reference to 'absolute(double), 'fun(int)'
cout << "More numbers? Please enter yes or no." << endl;
cin >> c;
}
while (!c.empty() && c[0] == 'y');
return 0;
}
Chapter6.h頭檔:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int fun(int a);
double absolute(double a);
int cnt();
fact.cpp:
#include <iostream>
#include <string>
#include <vector>
#include "Chapter6.h"
using namespace std;
//阶乘计算
int fun(int a)
{
int rec = 1;
while (a > 1)
{
rec *= a--;
}
return rec;
}
//返回绝对值
double absolute(double a)
{
if (a >= 0)
return a;
else
return -a;
}
編譯時要帶上所有
.cpp
檔名: