【问题标题】:C++ undefined references to functions in namespaceC++ 对命名空间中函数的未定义引用
【发布时间】:2013-03-25 03:24:27
【问题描述】:

这困扰了我一段时间。我有一个命名空间,我想在该命名空间中声明 C 风格的函数。所以我做了我认为正确的事情:

namespace test
{
    std::deque<unsigned> CSV_TO_DEQUE(const char* data);
    std::deque<unsigned> ZLIB64_TO_DEQUE(const char* data, int width, int height);

    std::string BASE64_DECODE(std::string const& encoded_string);
}

那么对于实现文件:

#include "theheaderfile.hpp"

using namespace test;

std::deque<unsigned> CSV_TO_DEQUE(const char* data)
{
     ...
}
std::deque<unsigned> ZLIB64_TO_DEQUE(const char* data, int width, int height)
{
     ...
}

std::string BASE64_DECODE(std::string const& encoded_string)
{
     ...
}

但是,在尝试实际调用函数时,我收到未定义的引用错误。文件链接,所以我不确定为什么引用未定义。

我还应该补充一点,如果我将函数从 test 命名空间中取出并将它们留在全局命名空间中,它们就可以顺利工作。

我想避免在标题中定义函数。这可能吗?

【问题讨论】:

  • c文件添加到项目中了吗?
  • 您只是定义了一个名称有点相似的新函数。您需要在命名空间中实际定义它们,或者通过使用头文件中的命名空间包装定义,或者通过限定名称std::deque&lt;unsigned&gt; test::CSV_TO_DEQUE(const char* data){/...}

标签: c++ c function namespaces


【解决方案1】:

using namespace 只会导入命名空间以供使用 - 它不会让您在该命名空间中定义函数。

您仍然需要在测试命名空间内定义函数:

namespace test {
    // your functions
};

【讨论】:

    【解决方案2】:

    定义如下:

    std::deque<unsigned> test::CSV_TO_DEQUE(const char* data)
    {
         ...
    }
    

    否则这只是全局命名空间中的一个新函数

    【讨论】:

      猜你喜欢
      • 2013-05-17
      • 1970-01-01
      • 2022-12-03
      • 2021-06-30
      • 1970-01-01
      • 2016-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多