Reputation: 23
Is it allowed to add Includes in C++ headers? like in this example.
#ifndef SOMEH_H
#define SOMEH_H
#include <fstream>
int funcofsomekind(){
ofstream myfile;
myfile.open ("Stackoverflow.stack");
myfile << "wolololol";
myfile.close();
}
#endif
Upvotes: 2
Views: 136
Reputation: 33646
yes, however - anyone who will include your header will get a lot of additional code into his namespace. what is more appropriate is to put the functions in a cpp file, and only include in the headers which which are required for the function prototypes - for example if your header had a function like
bool is_open(ostream &o);
you will have to include fstream.
Upvotes: 1
Reputation: 116197
You certainly add #include <something.h>
in your header, and it is often done if necessary.
However, it is considered very bad idea to put any code in headers (like you did). At the very least, including function twice via header in different source files will lead to duplicate function definition at linking time.
Upvotes: 2
Reputation: 18750
Literally all an #include
does (from your point of view) is take the text from the specified file and put it right in the spot where you tell it to. So yes you can put it in a header and sometimes have to.
You could even do something like
vector.txt
huge vector .....
std::vector<int> v {
#include vector.txt
}
Upvotes: 1