【发布时间】:2021-08-05 12:40:24
【问题描述】:
当我混合 C 和 C++ 代码时,当 Linux C 结构 statx 与 statx() Linux 系统调用同名时遇到了问题。
对于statx()系统调用在安装的glibc版本中不存在的情况,我实现了我自己的statx()版本。我尝试在匿名命名空间中实现一个备用的statx() 函数,但在这种情况下代码无法编译。
我试图将示例代码简化到最低程度。
#include <iostream>
struct statx {};
namespace {
void statx() { std::cout << "Function statx()\n"; }
}
int main()
{
statx(); // Compile error.
::statx(); // Calling constructor of struct instead of function statx().
}
用g++ 8编译的输出
g++ -std=c++17 -Wall -pedantic -Wextra str_fnc.cpp -o str_fnc
str_fnc.cpp: In function 'int main()':
str_fnc.cpp:13:5: error: reference to 'statx' is ambiguous
13 | statx(); // Compile error.
| ^~~~~
str_fnc.cpp:7:6: note: candidates are: 'void {anonymous}::statx()'
7 | void statx() { std::cout << "Function statx()\n"; }
| ^~~~~
str_fnc.cpp:3:8: note: 'struct statx'
3 | struct statx {};
| ^~~~~
str_fnc.cpp: At global scope:
str_fnc.cpp:7:6: warning: 'void {anonymous}::statx()' defined but not used [-Wunused-function]
7 | void statx() { std::cout << "Function statx()\n"; }
| ^~~~~
当我使用静态函数 statx() 而不是将其包含在匿名命名空间中时,代码编译并成功运行。
#include <iostream>
struct statx {};
static // The replacement anonymous namespace with static function.
void statx() { std::cout << "Function statx()\n"; }
int main()
{
statx();
::statx();
}
谁能解释为什么匿名命名空间中包含 statx() 的示例无法编译且不起作用?
【问题讨论】:
标签: c++ static namespaces