PDA

View Full Version : undefined reference


surreal5335
06-09-2010, 07:54 AM
I am working on a basic program calling by reference and value. When compiling I am told that my methods are undefined:



C:\DOCUME~1\ben\LOCALS~1\Temp/ccWdgp3y.o:stringProg.cpp:(.text+0x1d0): undefined
reference to `inputData(std::string&)'
C:\DOCUME~1\ben\LOCALS~1\Temp/ccWdgp3y.o:stringProg.cpp:(.text+0x1f4): undefined
reference to `outputData(std::string)'
collect2: ld returned 1 exit status



I have done many searches trying to identify the problem, but I cant see anything that applies to my code:


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

void inputData(string &);
void outputData(string);

int main() {

string myString = "myString";
inputData(myString);
outputData(myString);

}

void inputData(string s) {
cout << s << " by value" << endl;
}

void outputData(string &s) {
cout << s << " by reference" << endl;
}



This is just a setup for more to come, wanted to get this working before proceeding. I am sure its super basic, but I must be so rusty that I am just not seeing it.

#############################
Edited note
#############################

I just noticed my problem... silly mistake, I had the reference and value passing swapped from prototype to the actual method itself. I dont fully understand why prototypes are needed in C++, seems like a waste to me and another way to cause errors.

brad211987
06-09-2010, 03:02 PM
In short, prototypes are needed because C++ is a completely compiled language. When you compile your program, it makes references to all of the functions that you define so they can be used, and it does this in the order it reads them in. If you try to use a function, but no definition had been found yet, the compiler could not build the proper references to translate into machine code.

Technically you don't "need" prototypes, as long as your functions are declared before they are used, but it is simply much easier to use them instead of trying to juggle the order in which you specify functions. The prototypes usually end up in a header file where they can be imported into other programs as well.