Question about includes

Hello,
I've been trying to break my code up into separate files to keep everything neat. I've run into a problem though, many of my .cpp files are dependent on the same header files. I want to be as efficient as possible, and I've read about include guards and the like, which I understand. My question is, if I need to use #include <string> for multiple .cpp files, should I put that in each one? Or do I need to eliminate one of those includes to be efficient? I was thinking I could have a master include file, which could pull in all of my libraries and dependencies, and my .cpp files can use this single header. That way they all get the dependencies they need. Maybe I'm just misunderstanding the core concept, the problem is it's difficult to know if I'm doing it the wrong way, because I won't get any error for being inefficient.
Last edited on
if I need to use #include <string> for multiple .cpp files, should I put that in each one?

IMO yes.
I was thinking I could have a master include file, which could pull in all of my libraries and dependencies, and my .cpp files can use this single header.

This is very inefficient, you'll end up including many more unnecessary include files if you do this. I consider using one giant include file a very bad practice, always include the proper include file in the file it is needed, don't rely on some other file to include a required include file.

If you create your own header file, say myheader.h. You can include <string> within that header file, and then #include "myheader.h" in each of your cpp files.
It's not really that hard to understand. Include a file when it's needed.

I will say this, however: Beginners sometimes include a file in a header, even though it's not required in the header - it would, however, be required in the .cpp file.

Example:

messageprinter.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#ifndef _MESSAGEPRINTER_H_
#define _MESSAGEPRINTER_H_

#include <iostream>//not required in header, only cpp needs this.
#include <string>//this is required in the header, because of the function prototype for "void print(const std::string string)"

class MessagePrinter {
public :
	MessagePrinter() {}

	void print(const std::string string);
};

#endif 


messageprinter.cpp
1
2
3
4
5
#include "messageprinter.h"

void MessagePrinter::print(const std::string string) {
	std::cout << string << std::endl;
}


versus...

messageprinter.h
1
2
3
4
5
6
7
8
9
10
11
12
13
#ifndef _MESSAGEPRINTER_H_
#define _MESSAGEPRINTER_H_

#include <string>//this is required in the header, because of the function prototype for "void print(const std::string string)"

class MessagePrinter {
public :
	MessagePrinter() {}

	void print(const std::string string);
};

#endif 


messageprinter.cpp
1
2
3
4
5
6
#include "messageprinter.h"
#include <iostream>//cleaner

void MessagePrinter::print(const std::string string) {
	std::cout << string << std::endl;
}
Last edited on
Topic archived. No new replies allowed.