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

浏览:41日期:2023-03-15

问题描述

C++ Primer对于分离式编译的介绍很简单,于是自己想试一下怎么使用。按照以下代码运行,在main函数中运行fun()和absolute()时会提示没有定义函数。请问这是为什么?应该怎样做才能让代码顺利运行?

主函数:

#include <iostream>#include <string>#include <vector>#include 'Chapter6.h'using namespace std;//cnt函数每次被调用则返回值+1int 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; elsereturn -a;}

问题解答

回答1:

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

g++ main.cpp fact.cpp

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

相关文章: