Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

where should "include" be put in C++

Tags:

c++

include

I'm reading some c++ code and Notice that there are "#include" both in the header files and .cpp files . I guess if I move all the "#include" in the file, let's say foo.cpp, to its' header file foo.hh and let foo.cpp only include foo.hh the code should work anyway taking no account of issues like drawbacks , efficiency and etc .

I know my "all of sudden" idea must be in some way a bad idea, but what is the exact drawbacks of it? I'm new to c++ so I don't want to read lots of C++ book before I can answer this question by myself. so just drop the question here for your help . thanks in advance.

like image 397
Haiyuan Zhang Avatar asked Feb 19 '10 15:02

Haiyuan Zhang


People also ask

Where do I put #include?

Your #include s should be of header files, and each file (source or header) should #include the header files it needs.

Should includes be in header or C?

c') should include them itself, and not rely on its header to include them. The header should only include what users of the software need; not what the implementers need.

Where does include is written in the C program?

#include is a way of including a standard or user-defined file in the program and is mostly written at the beginning of any C/C++ program.

When we use #include in C?

The #include directive tells the C preprocessor to include the contents of the file specified in the input stream to the compiler and then continue with the rest of the original file.


2 Answers

As a rule, put your includes in the .cpp files when you can, and only in the .h files when that is not possible.

You can use forward declarations to remove the need to include headers from other headers in many cases: this can help reduce compilation time which can become a big issue as your project grows. This is a good habit to get into early on because trying to sort it out at a later date (when its already a problem) can be a complete nightmare.

The exception to this rule is templated classes (or functions): in order to use them you need to see the full definition, which usually means putting them in a header file.

like image 72
jkp Avatar answered Oct 13 '22 03:10

jkp


The include files in a header should only be those necessary to support that header. For example, if your header declares a vector, you should include vector, but there's no reason to include string. You should be able to have an empty program that only includes that single header file and will compile.

Within the source code, you need includes for everything you call, of course. If none of your headers required iostream but you needed it for the actual source, it should be included separately.

Include file pollution is, in my opinion, one of the worst forms of code rot.

edit: Heh. Looks like the parser eats the > and < symbols.

like image 25
jfawcett Avatar answered Oct 13 '22 02:10

jfawcett