首页  >  问答  >  正文

C++分离式编译如何应用?

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;
}
天蓬老师天蓬老师2700 天前877

全部回复(1)我来回复

  • typecho

    typecho2017-06-20 10:08:13

    编译时要带上所有 .cpp 文件名:

    g++ main.cpp fact.cpp

    回复
    0
  • 取消回复