Pofke1
Pofke1

Reputation: 31

Is declaring function in .h file is necessary if you only need it in .cpp file?

Is declaring a function in .h file necessary if I only need that function to work on one .cpp file? Declaring the function in a .cpp file seems to work as well.

Are there any performance differences, and is it ok to do so? Why is it an unusual practice to do so? (at least I haven't seen it)

Upvotes: 3

Views: 393

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 311088

Usually, functions are defined for using them more than one time and in different compilation units.

If a function should be used only in one compilation unit then you can define it in a cpp module. Moreover, it is desirable to make it with internal linkage. Otherwise, somebody can define a similar function with the same type in its own module and the ODR rule will be broken.

There is no performance difference because the compiler deals with compilation units that include all listed headers not a module without its headers.

Upvotes: 3

Acorn
Acorn

Reputation: 26186

If you are defining and calling a function in a single translation unit ("a .cpp"), then avoid declaring the function in a header file; unless you want to expose that functionality and have future callers from outside your translation unit.

Furthermore, you should put the function inside an anonymous namespace (or mark it static), so that readers (and the compiler) know that this function is private to the translation unit (internal linkage). This may imply that the function does not even get generated at all (the optimizer may decide to inline all callers).

In other words, do:

namespace {
    void foo() {
        // ...
    }
}

See as well Unnamed/anonymous namespaces vs. static functions and Superiority of unnamed namespace over static?

Upvotes: 2

Related Questions