3

Everyone points out the "one definition rule". I'm not going to define any of my stuff in c/cpp files but instead, i'm going to use them for only declarations.

One cpp file:

int add(int x, int y);

The other cpp file:

#include<one.cpp>
int add(int x, int y)
{
    return x + y;
}

The other cpp file:

#include<one.cpp>
int main()
{
    int result = add(2,2);
}

Basically the same thing, but instead of .h, i use .cpp. Difference? One definition rule is not applicable here. And yes, last question, why is everyone says that using headers and this technique reduces compile time? How exactly does that work?

  • The file suffixes are actually not essential. Essential is: what is provided to the compiler as translation unit (the file to compile) and what is included by that file. You may use any file suffix in both cases but this may confuse other readers... – Scheff's Cat Jul 11 '17 at 14:34
  • 7
    There is no difference; in fact, source files for the C++ standard library don't even have extensions. Any difference is only down to usage convention – meowgoesthedog Jul 11 '17 at 14:34
  • @spug makes sense then. Thanks you. What about the last question? –  Jul 11 '17 at 14:36
  • One question per question, Richard. Stack Overflow is not a discussion board. – Lightness Races in Orbit Jul 11 '17 at 14:42

1 Answers1

6

The compiler doesn't care about file extensions and thus there is no difference for the compiler. What matters here is that it is a well known and accepted convention that declarations (what something does) go into .h files and definitions & implementations (how something does that) go into .cpp files. If you don't follow this convention you will confuse other readers, which is a big problem if you're ever going to work on bigger projects. And then you'll be that guy that nobody wants to work with on a project anymore because you confuse other project members and then you'll lose your job just because you couldn't just follow that damn convention.


And yes, last question, why is everyone says that using headers and this technique reduces compile time? How exactly does that work?

I think you're referring to precompiled header files in which case this question has some good answers.

Hatted Rooster
  • 35,759
  • 6
  • 62
  • 122
  • Even if you're not using PCHs keeping definitions in the cpp files (instead of for example inlining methods in class declarations) as the compiler only has to compile the code once. It's also useful when only changing parts of the code to avoid full recompiles. – monoceres Jul 11 '17 at 14:42
  • "If you don't follow this convention you will confuse other readers" - you'll also confuse yourself a few months down the road when you forget how the code works (ask me how I know...) – Chris Parker Jul 11 '17 at 14:53