Re: Header file question
On Wednesday, March 25, 2015 at 6:46:43 AM UTC-7, Joseph Hesse wrote:
The following 3 file program was constructed so I could get advice with=
header file inclusion. The program compiles and run fine.
= Funcs.h =====================
=========
#ifndef FUNCS_H
#define FUNCS_H
#include <vector>
double sum(std::vector<double> &vd);
#endif
= Funcs.cpp ====================
========
#include "Funcs.h"
double sum(std::vector<double> &vd)
{
double s = 0.0;
for(const double &d : vd)
s += d;
return s;
}
= Test.cpp =====================
========
#include <iostream>
#include "Funcs.h"
int main()
{
std::vector<double> numbers = {1.5, 2.5, 3.5, 4.5};
std::cout << "The sum is " << sum(numbers) << std::endl;
return 0;
}
=========================
===============
1. In Funcs.cpp the file Funcs.h was included since it seems like best
practices for an X.cpp to always include an X.h. However one could
argue that someone reading Funcs.cpp would see the use of the type
vector<double> and therefore #include <vector> should also be there,
even though it is redundant.
2. Same question for Test.cpp. Should #include <vector> be there since=
it already comes from #include Funcs.h?
Thank you,
Joe
I am not aware of any best practices that may exist in this regard. Persona=
lly, if an include is in the header I purposely don't put it in the cpp fil=
e. It obviously serves no purpose to the code, so only possibly to the code=
r -- and in my case it's useless duplicate lines -- when I end up "removing=
" the header in the future, I may end up still including it anyway, is my m=
ental perspective. Of course, if a communal project had a standard, I would=
go with that when participating.