C++ 函数的多重定义
我一直在犯这个错误 /tmp/ccKGPdrx.o:在函数C++ 函数的多重定义,c++,string,c++11,C++,String,C++11,我一直在犯这个错误 /tmp/ccKGPdrx.o:在函数FindWords(std::string)”中: app2.cpp:(.text+0x0)FindWords(std::string)的多个定义 /tmp/ccDIMHPc.o:main.cpp:(.text+0x0):首先在这里定义 collect2:错误:ld返回了1个退出状态 我的app2.cpp文件 #include <fstream> #include <iostream> std::string F
FindWords(std::string)”中:
app2.cpp:(.text+0x0)
FindWords(std::string)的多个定义
/tmp/ccDIMHPc.o:main.cpp:(.text+0x0):首先在这里定义
collect2:错误:ld返回了1个退出状态
我的app2.cpp文件
#include <fstream>
#include <iostream>
std::string FindWords(std::string str)
{
std::ifstream iFile("in.txt");
std::string x;
while (true) {
iFile >> x;
if (x.compare(0,str.size(),str) == 0) {
std::cout << x;
}
if( iFile.eof() ) break;
}
return x;
}
#包括
#包括
std::string FindWords(std::string str)
{
std::ifstream iFile(“in.txt”);
std::字符串x;
while(true){
i文件>>x;
如果(x.compare(0,str.size(),str)==0){
这是因为这条线:
#include "app2.cpp"
您不应该包括类的cpp
文件。相反,您应该链接它,并包括标题:
附件2.h
#include <string>
std::string FindWords(std::string str);
#包括
std::string FindWords(std::string str);
出现错误的原因是您在带有main的模块中包含了moduleapp2.cpp。因此这两个模块都已编译,并且有两个相同函数的定义
您应该在某些头中声明函数,并在模块app2.cpp中保留其定义,并将此头包含在两个模块中
考虑到该函数的代码无效。由于缺少一个右大括号,因此不应编译该函数。此外,它将返回上次读取的字符串,而不是与str不#包含.cpp文件同时出现的字符串。我怀疑OP正在链接它,并包含它。@Beta是的,这就是probab因为他有多种定义。
#include <string>
std::string FindWords(std::string str);