【发布时间】: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