通过将一组与输入和输出相关的函数与程序的其他部分分开的 Action ,当将头文件中的函数放在命名空间中时,我遇到了编译文件的问题。编译以下文件:
#include "IO.h"
int main()
{
testFunction("yikes");
}
#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;
}
在Windows 10 Home上,编译命令为
g++ -std=c++11 main.cpp IO.cpp
,编译器为TDM-GCC的x86_64-w64-mingw32。 最佳答案
如果将函数的声明更改为在命名空间中,则还需要在该命名空间中实现该函数。
函数的签名将为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) { ... }