为什么命名空间的使用会破坏 MinGW 编译?
Why does namespace usage break MinGW compilation?
通过将一组输入和输出相关函数与程序的其他部分分离的行为,当头文件中的函数被放置在命名空间中时,我遇到了编译文件的问题。编译以下文件:
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
,编译器是x86_64-w64-mingw32 来自TDM-GCC,在Windows 10 Home。
如果您将函数的声明更改为在命名空间中,您也需要在该命名空间中实现该函数。
你的函数的签名是 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) { ... }
通过将一组输入和输出相关函数与程序的其他部分分离的行为,当头文件中的函数被放置在命名空间中时,我遇到了编译文件的问题。编译以下文件:
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
,编译器是x86_64-w64-mingw32 来自TDM-GCC,在Windows 10 Home。
如果您将函数的声明更改为在命名空间中,您也需要在该命名空间中实现该函数。
你的函数的签名是 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) { ... }