c++header-filesfile-organization

Multiple structures defined inside a header file - Should I move them out in separate h and cpp files


One of my previous colleagues wrote a huge header file which has around 100 odd structures with inline member function definitions. This structure file is included in most class implementations(cpp files) and header files(don't know why my colleague didn't use forward declarations)

Not only it is a nightmare to read such a huge header file, but its difficulty to track problems due to compiler complaining of multiple definitions and circular references now and then. Overall compilation process is also really slow.

To fix many such issues, I moved inclusion of this header file from other header files to cpp files (wherever possible) and used forward declarations of only relevant structures. Still I continue to get strange multiple definition errors like "fatal error LNK1169: one or more multiply defined symbols found".

I am now contemplating whether I should refactor this structure header file and separate the structure declaration and definition in separate h/cpp files for each and every structure. Though it will be painful and time consuming to do this without refactoring tools in Visual Studio, is this a good approach to solve such issues ?

PS: This question is related to following question : Multiple classes in a header file vs. a single header file per class


Solution

  • When challenged with a major refactoring like this, you will most likely do one of the following approaches: refactor in bulk or do this incrementally.

    The advantage of doing it in bulk is that you will go through the code very fast (compared to incrementally) however if you end up with some mistake, it can take quite a lot of time before you get it fixed.

    Doing this incrementally and splitting of the classes one by one, you reduce the risk of time-consuming mistakes, however it will take some more time.

    Personally, I would try to combine the 2 approaches:

    Something that I've already found useful for creating self-sufficient header files is to precompile your headers. This compilation will fail when you haven't included the right data.