DarkoNaito_09
DarkoNaito_09

Reputation: 101

Best Way to Deal With Headers and Source Files

I always arranged my C++ headers and source files this way:

prog.h

#include <iostream>
class Prog
{
    public:
        Prog(std::string);
        ~Prog();
        
        void printName();
        
    private:
        std::string name;
};

#include "prog.cpp"

prog.cpp

Prog::Prog(std::string n):
    name(n)
{
    std::cout << "Program \"" << name << "\" started.\n";
}

Prog::~Prog()
{
    std::cout << "Program \"" << name << "\" ended.\n";
}

void Prog::printName()
{
    std::cout << "Program name is: \"" << name << "\".\n";
}

main.cpp

#include "prog.h"

int main()
{
    Prog prog {"MyCalculator"};
    
    prog.printName();
    
    return 0;
}

But I recently discovered that it's common to arrange them this other way:

prog.h

class Prog
{
    public:
        Prog(std::string);
        ~Prog();
        
        void printName();
        
    private:
        std::string name;
};

prog.cpp

#include <iostream>
#include "prog.h"

Prog::Prog(std::string n):
    name(n)
{
    std::cout << "Program \"" << name << "\" started.\n";
}

Prog::~Prog()
{
    std::cout << "Program \"" << name << "\" ended.\n";
}

void Prog::printName()
{
    std::cout << "Program name is: \"" << name << "\".\n";
}

main.cpp

#include <iostream>
#include "prog.h"

int main()
{
    Prog prog {"MyCalculator"};
    
    prog.printName();
    
    return 0;
}

I find the first method more convenient, so is there any reason why I should prefer the second method over the first one?

Upvotes: 0

Views: 457

Answers (2)

Miguel
Miguel

Reputation: 2219

Header files shouldn't include source code.

  • I think the first method could provoke dependency errors in a complex enough project (for example, using circular dependencies), because don't separate declaration and definition.
  • The compilation time is faster in the second one, because you can compile each source file separately.

Also, you might find this question useful.

Upvotes: 2

Giogre
Giogre

Reputation: 1572

The first version is what the book "Accelerated C++" (ed. 2000) suggests to do when first introducing header files for class declarations.

I suppose the second version can be seen as more elegant because it groups together all #include pre-compiler statements at the beginning of the program.

Upvotes: 0

Related Questions