我创建了三个单独的文件。第一个是main.cpp,第二个是名为“statistics.h”的头文件,它有两个函数的声明,我得到错误,而第三个是一个名为statistics.cpp的文件,它保存了两个函数的实现
这是我的主要文件:
#include <iostream>
#include "statistics.h"
using namespace std;
int main()
{
cout<<"This program provides the average and the standard deviation of 1,2,3 or 4 numbers."<< endl;
while(true){
start:
unsigned int howmany;
cout<<endl;
cout<<"How many numbers do u wish to receive as input?? ";
cin >> howmany;
if (howmany>4){
cout<<"You should pick at most 4 numbers u idiot!!!"<< endl<<endl;
goto start;
}
if(howmany==0){
return 0;
}
cout<< endl;
double nums[howmany];
for (int i=0;i<howmany;i++){
cout<<"Give me the number "<<i+1<<":";
cin>>nums[i];
}
double avg=average(nums,howmany); /////////////////////////////
double stdev=standard_deviation(nums,howmany,avg); ////////////////////
cout<< endl<<"Average: "<<avg<<". Standard Deviation: "<< stdev<< endl;
}
}
我的头文件是:
#ifndef STATISTICS_H_INCLUDED
#define STATISTICS_H_INCLUDED
double average(double ar[],int hm);
double standard_deviation(double ar[],int hm,double avrg);
#endif // STATISTICS_H_INCLUDED
我的实现文件statistics.cpp是:
#include<iostream>
#include"statistics.h"
#include <math.h>
using namespace std;
double average(double ar[],int hm){
double sum=0.0;
double average;
for(int i=0;i<hm;i++){
sum+=ar[i];
}
average=sum/hm;
return average;
}
double standard_deviation(double ar[],int hm,double avrg){
double std_dev;
double sum=0;
double ans;
for(int i=0;i<hm;i++){
sum+= ((ar[i]-avrg)*(ar[i]-avrg));
}
ans=sqrt(sum/hm);
return ans;
}
我在主文件中收到错误(我已经用连续的////////标记了相应的行)。可能有什么不对?我确信这是我的愚蠢行为。
当我使用代码块时,我终于找到了解决方案。我只需要将#include“statistics.cpp”添加到我的main.cpp文件中。
答案 0 :(得分:2)
您忘记将statistics.o与main.o链接在一起,因此您的假设可执行文件将不包含函数定义。
(假设的可执行文件因此不存在,因此您将收到链接器错误。)
你写的东西在哪里:
g++ main.cpp -o myExecutable
代替写:
g++ main.cpp statistics.cpp -o myExecutable
你写的东西在哪里:
g++ -c main.cpp
g++ main.o -o myExecutable
代替写:
g++ -c main.cpp
g++ -c statistics.cpp
g++ main.o statistics.o -o myExecutable
如果您仍然遇到问题,请尝试将提交文件名的顺序撤消到g++
(尽管上述内容应该是正确的)。
顺便说一句,您不能定义具有可变维度的数组。请改用std::vector
。
答案 1 :(得分:1)
当我使用代码块时,我终于找到了解决方案。我只需要将#include“statistics.cpp”添加到我的main.cpp文件中。
!!!这是 NOT 解决方案。不包含实现文件。你将陷入绝望,衰败和混乱的陷阱。
使用头文件一切都很好。您只需要告诉IDE将这两个文件编译为单个项目。请参阅文档。