C++分离式编译如何应用?
本文介绍了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;
}
解决方案
编译时要带上所有 .cpp
文件名:
g++ main.cpp fact.cpp
这篇关于C++分离式编译如何应用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文