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
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.
CodePudding user response:
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].