Tom Lilletveit
Tom Lilletveit

Reputation: 2002

C++ passing reference to string itself, won´t compile

I am using Xcode and it refuses to compile when passing reference to the string object itself.

(string &text, string remove)

without & it compiles. Is it my code that is wrong or could it be something with the project file?

this is the compiler error:

Undefined symbols for architecture i386:
"removeLetters3(std::string, std::string)", referenced from:
  Main() in narcissism.o
 ld: symbol(s) not found for architecture i386
 clang: error: linker command failed with exit code 1 (use -v to see invocation)

Code:

string removeLetters3(string &text, string remove)
{
for (int i = 0; i < remove.length(); i++)
{
    int pos = 0;

    while ((pos = text.find(remove[i], pos)) != string :: npos)
    {
        text.replace(pos, 1, "");
    }
}
return "";
}

and here is how the function is called:

string text;
string rletter;
removeLetters3(text, rletter);

Upvotes: 0

Views: 128

Answers (1)

bitmask
bitmask

Reputation: 34628

There is nothing wrong with your code but judging from your error I would assume that the declaration that the caller sees is this:

string removeLetters3(string text, string remove);

While your implementation reads

string removeLetters3(string &text, string remove) {

So when your linker tries to find the implementation of the first one it fails because there is no such implementation.

This is evidenced by the error:

Undefined symbols for architecture i386:
"removeLetters3(std::string, std::string)", referenced from:
  Main() in narcissism.o

notice the signature. It is not saying:

Undefined symbols for architecture i386:
"removeLetters3(std::string&, std::string)", referenced from:
  Main() in narcissism.o

Upvotes: 3

Related Questions