引用全局命名空间中的某个内容

referencing something from global namespace?

本文关键字:全局 命名空间 引用      更新时间:2023-10-16

这确实很琐碎,但我遇到了一个意想不到的错误。

我有一些代码在名称空间中

以下是表示我的代码结构的一些伪代码:

namespace A {
    void init() {
        initialize_kitchen_sink();
    }
    #include "operations.h" // declares shake_and_bake()
    void foo() {            
        shake_and_bake();
    }
    void cleanup() {
        // do nothin' cuz i'm a slob
    }
}

错误:

undefined reference to `A::shake_and_bake`

事实证明,将#include移动到命名空间之外会修复它。

实际上,include将在A命名空间内声明operations.h中的所有函数。然后,它将徒劳地搜索实现。

我想,与其删除我的整个帖子,我还不如把它留到那一分钟,让其他人偶然发现类似的问题并获得启发。

为了准确地回答您的问题,您可以使用::作为您的第一个语句来引用全局名称空间中的某些内容,如:

 void foo() {            
        ::shake_and_bake();
    }

当然,对于这种特殊情况,你的答案是正确的。