通过将一组与输入和输出相关的功能与程序的其他部分分离的动作,当头文件中的函数放置在命名空间中时,我遇到了编译文件的问题。编译以下文件:
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。
答案 0 :(得分:4)
如果将函数的声明更改为在命名空间中,则还需要在此命名空间中实现该函数。
函数的签名将为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) { ... }