Organize includes

Viewed 5600
  • Is there some preferred way to organize ones include directives?
  • Is it better to include the files you need in the .cpp file instead of the .h file? Are the translation units affected somehow?
  • How about if I need it in both the .h file and .cpp file, should I just include it in the .h file? Will it matter?
  • Is it a good practice to keep the already defined files in a precompiled header (stdafx.h), for instance std and third party libraries? How about my own files, should I include them in a stdafx.h file along the way as I create them?

// myClass.h
#include <string>
// ^-------- should I include it here? --------

class myClass{
    myClass();
    ~myClass();

    int calculation()
};

// myClass.cpp
#include "myClass.h"
#include <string>
//  ^-------- or maybe here?  --------

[..]

int myClass::calculation(){
    std::string someString = "Hello World";
    return someString.length();
}


// stdafx.h
#include <string.h>
// ^--------- or perhaps here, and then include stdafx.h everywhere? -------
6 Answers
Related