Petr
Petr

Reputation: 14495

How do I prevent include breakage

I have a code that contains huge number of cpp / header files. My problem now is, that because many include each other, I occasionally get into a situation that my code doesn't compile, unless I reorder the #include directives in random files, which is now necessary basically with creation of any other header file.

This is really very annoying; is there any tip how should I write my c++ code in order to prevent complications with #include? I would prefer to split my source code to as many files as possible so that cooperation with other programmers (using git or svn) is easier (more files == lower number of edit conflicts).

One of things that help me now is forward declaration, when I declare the classes from other headers into other files. That helps sometimes, but doesn't resolve all issues; sometimes I just need to change order of #includes in random header files or merge multiple files.

Upvotes: 0

Views: 132

Answers (1)

anatolyg
anatolyg

Reputation: 28271

Not a panacea, but the following guideline helps me a lot.

Assuming your code is composed of files like MyClassXyz.cpp with corresponding MyClassXyz.h, one class per source file, every cpp-file should include its corresponding header file first. That is, MyClassXyz.cpp must start with the following line:

// (possibly after comments)
#include "MyClassXyz.h"

This ensures that MyClassXyz.h includes all header files (or forward declarations) necessary for its compilation.

I often see code that uses an opposite convention (#includeing most general header files first), for example, MyClassXyz.cpp starts with

#include <vector>
#include <iosfwd>
#include "blah.h"
#include "mytypes.h"
#include "MyClassXyz.h"

And MyClassXyz.h "goes straight to the point" using stuff defined in the additional headers:

#pragma once
// "#include <vector>" missing - a hidden error!
// "#include <iosfwd>" missing - a hidden error!
class MyClassXyz
{
    std::vector<int> v;
    friend std::ostream& operator<<(...);
    ...
}

While this compiles OK, it gives enormous headaches of the type you describe, when trying to use the class MyClassXyz in some other source file.

Upvotes: 1

Related Questions