Search code examples
c++headerdependenciesworkspaceorganization

How to organize header/code files in C++ if I want only well-architectured workspace but not necessarily separated compilation?


I began to write my program in a single cpp-file but now I have too much code so I decided to separate it. But the problem is that I have many constants, includes and some other things that I want to have all in one place. Unfortunately, all of them are needed by dependent parts of code so I can't do it with usual include files.

What would help me?

(I write under Linux and compile with command-line)

(Sorry for my English :))


Solution

  • As Hristo said, you should generally write the definitions in header files and write the implementation in the source code files.

    To answer your question however:

    But the problem is that I have many constants, includes and some other things that I want to have all in one place.

    What I've typically done is create a single file called something like "common.h" or "defs.h" (I took the idea from Doom...) and that file has many defines that you find you need throughout your entire program. If you are using constants, declare the constants in the header file like so:

        extern const int MAX_SOMETHING;
        extern const bool TRUTH_VALUE;
    

    and make a complementary source file (defs.cpp or common.cpp) that defines these constants:

        const int MAX_SOMETHING = 5;
        const bool TRUTH_VALUE = true;
    

    so now when you include the common/defs.h in other source files, the extern keyword will tell that source file that the definition is in another source file (its in the common/defs.cpp) so it will find the definition in there, and you can use it anywhere where you have included common/defs.cpp.