undefined reference to function code blocks

Michael harris picture Michael harris · Sep 17, 2013 · Viewed 7k times · Source

main.cpp

#include <iostream>
#include <string>
using namespace std;

void echo(string);

int main()
{
    echo("hello");
    cout << "Hello world!" << endl;
    return 0;
}

print.cpp

#include <iostream>
#include <string>
void echo(string code){
   cout << code;
}

After compiling the code in code blocks 12.11, it gives me that error:

undefined reference to `echo(std::string)

I use windows 7 x64. I have added the directory; Project>build options > search directories and added the current working directory. All the files are in one console project in code blocks

Answer

user142650 picture user142650 · Sep 17, 2013

I believe you should read up a bit more on namespaces usage. You are missing std in print.cpp.

Generally, while starting to learn cpp or getting a grip of the language you should always try writing full names of the classes along with the namespaces. Eventually with practice and some oversights (like now) you will learn why you really need them. In a nutshell namespaces are great:

  • When you are writing code over multiple files
  • Compartmentalize your code into separate blocks.

Also, using namespace std; should be used within cpp files mostly (otherwise headers get mangled up.

Anyways, try changing your code to this:

#include <iostream>
#include <string>
void echo(std::string code){
    std::cout << code;
}

Then your results will look like this:

 > g++ main.cpp print.cpp -o a.out

 > ./a.out
helloHello world!