How to apply C++ separated compilation?
天蓬老师
天蓬老师 2017-06-20 10:06:13
0
1
832

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

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(1)
typecho

Please bring all .cpp files when compiling:

g++ main.cpp fact.cpp

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!