Reputation: 1
I keep getting this error
/tmp/ccKGPdrx.o: In function FindWords(std::string)':
app2.cpp:(.text+0x0): multiple definition of
FindWords(std::string)'
/tmp/ccDIMHPc.o:main.cpp:(.text+0x0): first defined here
collect2: error: ld returned 1 exit status
My app2.cpp file
#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;
}
my main file
#include <iostream>
#include "app2.cpp"
#include <fstream>
int main() {
std::string s = FindWords("cha");
return 0;
}
It's just a simple code that reads in strings from a file and gets a string as an input. If any string from the file matches with the input string then it prints it.
Upvotes: 0
Views: 167
Reputation: 311126
The reason of the error is that you included module app2.cpp in the module with main. So the both modules were compiled and there are two definitions of the same function.
You should declare the function in some header keeping its definition in module app2.cpp and include this header in the both modules.
Take into account that the code of the function is invalid. It shall not be compiled because one closing brace is absent. Also it will return the last read string instead of the string that coinsides with str
Upvotes: 0
Reputation: 727047
This is because of this line:
#include "app2.cpp"
You should not be including the cpp
file for the class. Instead, you should be linking it, and including the header:
app2.h
#include <string>
std::string FindWords(std::string str);
Upvotes: 2