【问题标题】:Why does namespace usage break MinGW compilation?为什么命名空间使用会破坏 MinGW 编译?
【发布时间】:2019-01-04 00:57:41
【问题描述】:

通过将一组输入和输出相关函数与程序的其他部分分离的行为,当头文件中的函数放置在命名空间中时,我遇到了编译文件的问题。以下文件编译:

main.cpp

#include "IO.h"
int main()
{
    testFunction("yikes");
}

IO.h

#ifndef IO_H_INCLUDED
#define IO_H_INCLUDED
#include <string>
void testFunction(const std::string &text);
#endif    

但是,testFunction 放置在命名空间中时:

#ifndef IO_H_INCLUDED
#define IO_H_INCLUDED
#include <string>

// IO.h
namespace IO
{
    void testFunction(const std::string &text);
}
#endif

在 IO.h 中,然后以 IO::testFunction 调用,编译失败,抛出

undefined reference to `IO::testFunction(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)'
collect2.exe: error: ld returned 1 exit status`

在每种情况下,IO.cpp 都是

#include <string>
#include <iostream>
void testFunction(const std::string &text)
{
    std::cout << text << std::endl;
}

编译命令为g++ -std=c++11 main.cpp IO.cpp,编译器为Windows 10 Home上来自TDM-GCC的x86_64-w64-mingw32。

【问题讨论】:

  • 您还需要将您的实现放入命名空间。 void IO::testFunction(...) { ... }
  • 您的基本示例很好,但是您应该在添加命名空间之后添加代码现在的样子,以便我们可以准确地看到您在做什么。 @Kanjiu 很可能是正确的,但是如果没有完整的“后”代码示例,就无法确定。
  • 时髦。谢谢你。这证明了@Kanjiu 的假设。

标签: c++ compiler-errors mingw separation-of-concerns


【解决方案1】:

如果您将函数的声明更改为在命名空间中,您还需要在此命名空间中实现该函数。

你的函数的签名是IO::testFunction(...),但你只实现了testFunction(...),所以没有IO::testFunction(...)的实现

头文件(IO.h):

namespace IO {
    void testFunction(const std::string &text);
}

cpp文件(IO.cpp):

#include "IO.h"

// either do this
namespace IO {
    void testFunction(const std::string &text) { ... }
    // more functions in namespace
}


// or this
void IO::testFunction(const std::string &text) { ... }

【讨论】:

  • namespace IO { ... } 有效,但奇怪的是第二个选项不起作用,MinGW 在编译时抛出 error: 'IO' has not been declared。这是为什么呢?
  • @MushroomMan 确实 IO.cpp 包含 IO.h,因此编译器可以在看到 IO::testFunction() 中的 IO 之前看到 namespace IO 的声明?
  • 我也将包含添加到我的答案中@RemyLebeau
  • @RemyLabeau 唉,它没有;这就是问题所在,谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-25
  • 1970-01-01
  • 2021-08-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多