【发布时间】:2018-12-11 09:56:03
【问题描述】:
考虑以下场景:
源.cpp
int add(int a, int b) { return a + b; } // function in global scope
头文件.h
namespace ns
{
class A
{
public:
void do()
{
...
...
method();
...
...
}
private:
int method()
{
...
...
int add(int a, int b); // forward declaration
auto result = add(5, 10); // function call
...
...
// do something with result
}
};
}
在 Windows(MS 编译器) 上,上述操作按预期工作。
在 Linux (GCC) 上,它会导致链接器错误,其中方法 add() 被报告为 未定义的引用。
而且,错误说明编译器试图在ns命名空间下寻找add(),但在全局命名空间中明确定义。
在链接前向声明的方法时,Linux 上的 GCC 的行为是否与 Windows 上的 MS 编译器不同?我该如何解决这个问题?
【问题讨论】:
标签: c++11 gcc linker forward-declaration