在 .h 和 .cpp 中单独声明和定义但非 class 函数?
Separate declaration and definition in .h and .cpp but NON-class functions?
我习惯于编写不必在命名空间中的 class 中的函数,所以我想知道是否可以在源文件和头文件中将它们分开:
utilities.hpp:
namespace nms {
static void process();
};
utilities.cpp
void nms::process(){/*...*/}
但是像这样我只得到一个错误:main.cpp:(.text+0x5): undefined reference to 'nms::process()'
。所以我想知道这是否可行。
在 header 文件中 utilities.hpp
:
namespace nms {
static void process();
};
static
表示该函数具有 内部 链接,这意味着它 声明 每个翻译单元的唯一函数,其中header 已包括在内。
然而,对应唯一(内部链接)process()
函数具有 定义 的唯一翻译单元 (TU) 位于与 utilities.cpp
,而对于包含 utilities.hpp
的任何其他源文件,不存在 TU-local process()
函数的定义。
这解释了为什么在 utilities.cpp
以外的位置出现未定义的引用错误,只要该使用站点需要 TU-local 函数的定义。删除静态,publically-intended process()
函数将没有内部链接。
... but NON-class functions?
不幸的是,static
关键字在 C++ 中的含义非常重载,class 成员函数的 static
与命名空间作用域函数的含义不同,因为 process()
以上。对于 class 成员函数,使用 static
关键字使 static 成员 ([class.static].
我习惯于编写不必在命名空间中的 class 中的函数,所以我想知道是否可以在源文件和头文件中将它们分开:
utilities.hpp:
namespace nms {
static void process();
};
utilities.cpp
void nms::process(){/*...*/}
但是像这样我只得到一个错误:main.cpp:(.text+0x5): undefined reference to 'nms::process()'
。所以我想知道这是否可行。
在 header 文件中 utilities.hpp
:
namespace nms {
static void process();
};
static
表示该函数具有 内部 链接,这意味着它 声明 每个翻译单元的唯一函数,其中header 已包括在内。
然而,对应唯一(内部链接)process()
函数具有 定义 的唯一翻译单元 (TU) 位于与 utilities.cpp
,而对于包含 utilities.hpp
的任何其他源文件,不存在 TU-local process()
函数的定义。
这解释了为什么在 utilities.cpp
以外的位置出现未定义的引用错误,只要该使用站点需要 TU-local 函数的定义。删除静态,publically-intended process()
函数将没有内部链接。
... but NON-class functions?
不幸的是,static
关键字在 C++ 中的含义非常重载,class 成员函数的 static
与命名空间作用域函数的含义不同,因为 process()
以上。对于 class 成员函数,使用 static
关键字使 static 成员 ([class.static].