简体   繁体   中英

The function extension in C++ definition file (CPP)

In C++ definition file (.cpp), sometimes I can define small functions to be invoked, for example:

// Class declaration 
// Myclass.h
Class Myclass
{
...
  void Classfunction();
...
}
// Class defination 
// Myclass.cpp
#include "Myclass.h"
...
void helper_fun()
{
 ...
}
...
void Myclass::Classfunction()
{
...
  helper_fun();
...
}

In the above example, we can see void helper_fun() is declared and defined in the .cpp file. The purpose of this function is to be invoked by the functions that have been defined in the class. Of course, the helper_fun can be declared in the head file first and then defined in the implementation file. My question is whether this is a good practice for C++ code writing. Moreover, does this practice have some bad effects? Thanks!

It would be good practice to have the helper_fun defined in an anonymous namespace within the source file.

Like this:

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

Reason being that if another helper_fun is defined in another source file with the same signature, you wouldn't have any risk with linkage errors. It's not to say that there will be, but rather, there could be one.

Also, you shouldn't put functions in your header if it's not going to be used outside of the respective source file.

Having local helper functions in the source files are very common. Normally they are either declared as static (eg static void helper_fun() { } ) or in an anonymous namespace (eg namespace { void helper_fun() { } } ).

Making the functions static or having them in an anonymous namespace is so that they wont be callable from the outside, and so that you can have more local functions with the same name.

If, however, you want to call the function from other source files, then define the function normally, and add a declaration in the header file.

If you need it to be public, and included in other files via the header file. Then put it there.

Otherwise there's no reason for it to be in the header.

If you declare helper_fun in the header, it becomes visible to users of Myclass.h . Do you want helper_fun to be used elsewhere?

By keeping it solely within Myclass.cpp you ensure it can only be used by code within Myclass.cpp .

Of course declare functions in .cpp files is ok. It is helper function, so, you shouldn't give its declaration to user. You can use anonymous namespace for internal linkage (by default functions has external linkage).

An unnamed namespace or a namespace declared directly or indirectly within an unnamed namespace has internal linkage.

like this

namespace
{
// helper_fun has internal linkage.
void helper_fun()
{
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM