Home  >  Q&A  >  body text

How to apply C++ separated compilation?

C Primer’s introduction to separate compilation is very simple, so I wanted to try how to use it myself. Run the following code. When running fun() and absolute() in the main function, you will be prompted that no function is defined. Is that why? What should be done to make the code run smoothly?

Main function:

#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 header file:

#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;
}
天蓬老师天蓬老师2649 days ago834

reply all(1)I'll reply

  • typecho

    typecho2017-06-20 10:08:13

    Please bring all .cpp files when compiling:

    g++ main.cpp fact.cpp

    reply
    0
  • Cancelreply