Nicholas Nicholas - 8 months ago 52
C++ Question

Is it okay to have a function declaration more than once in a single cpp file?

Based on the answer by sbi to this question,

An identifier can be declared as often as you want (statement 1)

But isn't it true that

include guard
in C++ just prevents the function declarations from
showing up more than once in a single source file (statement 2)


My question is: why this contradiction? Or have I misunderstood either of the two statements?

Answer Source

Yes, you can declare (but not define) a function multiple times in a single translation unit. And yes, include guards usually prevent this, but that is not their only purpose. Headers often define classes, templates, and inline functions; the header guard is needed to prevent multiple definitions of those entities from appearing in a single translation unit. Header guards also help prevent an exponential blowup in the number of times a header gets pasted into a translation unit.