Search code examples
c++preprocessorcode-splitting

Is it possible to separately compile class code in c++ (like .h and .cpp) while only using one file?


I'm trying to get the benefits of splitting without two files. Split compilation without splitting storage.

I understand the benefits of separating .h and .cpp files, but I really dislike having the files be separate, specifically when the classes are tiny and each file could fit on the same page.

Is there a precompiler option, or perhaps any other trick which would allow me to keep the benefits of separation, while having the text all in the same place? For example:

EDIT: please do not focus too much on this example. It was meant to show off an imaginary pre-processor arg #CPP_SPLIT. The actual code is unimportant, please, please ignore it.

// TinyClass.h
class TinyClass {
  TinyClass();
  int answerToLife();
}

// the following is a fake compiler arg
// in this example it would be totally unnecessary, 
// but many of my classes have some form of circular referencing
// and can not include all the code in the .h file
#CPP_SPLIT

TinyClass::TinyClass() {}
TinyClass::answerToLife() { return 42; }

#CPP_SPLIT_END

Solution

  • I'm not sure it's worth the effort, but you could place the contents of your .cpp file into #ifdef'd sections, like this:

    #ifdef PART_ONE
    
    [...]
    
    #endif
    
    #ifdef PART_TWO
    
    [...]
    
    #endif
    
    #ifdef PART_THREE
    
    [...]
    
    #endif
    

    ... and then recompile the file over multiple passes, like this:

    g++ -DPART_ONE   -opart1.o myfile.cpp
    g++ -DPART_TWO   -opart2.o myfile.cpp
    g++ -DPART_THREE -opart3.o myfile.cpp
    g++ -o a.out part1.o part2.o part3.o