Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Separate declaration and definition in .h and .cpp but NON-class functions?

I have the practice of writing functions that do not have to be in a class in namespaces, so I would like to know if can separate them in source and headers files:

utilities.hpp:

namespace nms {
    static void process();
};

utilities.cpp

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

void nms::process(){/*...*/}

But like this I only get an error: main.cpp:(.text+0x5): undefined reference to 'nms::process()'. So i would like to know if this is possible in anyway.

>Solution :

In the header file utilities.hpp:

namespace nms {
    static void process();
};

static means the function has internal linkage, meaning it declares a unique function for each translation unit in which the header is included.

The only translation unit (TU) for which the corresponding unique (internal linkage) process() function has a definition is, however, in the TU associated with utilities.cpp, whereas for any other source file which includes utilities.hpp, no definition exists for the TU-local process() function.

This explains why you get undefined reference errors in locations other than utilities.cpp, as soon as that use site requires a definition for the TU-local function. Remove static and the publically-intended process() function will not have internal linkage.


… but NON-class functions?

The static keyword is unfortunately quite overloaded in meaning in C++, and static for class member function does not mean the same thing as for a namespace scope function as process() above. For class member function, using the static keyword makes the static members ([class.static].

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading