tags:

views:

53

answers:

4

I'm trying to create a very simple function in c++ however I keep getting a "Link error".

My code:

#include <iostream>

using namespace std ;


int fun(int,int);

main(){
    int width,height,w,h,mult;

    cin>>width;
    cin>>height;

    mult = fun(width,height);

    int fun(int w,int h);{
        w * h ;
        }

    cout << mult ; 

}

The error:

[Linker error] undefined reference to `fun(int, int)' 
ld returned 1 exit status 
+6  A: 

There is no implementation of fun(int, int) anywhere. The module which implements it should be linked in with this. Or you should write the function in the module above, perhaps where the prototype is.

It appears there is a failed attempt to define the function midway:

int fun(int w,int h);{
    w * h ;
    }

What this actually does it declare (again) that there is some function int fun(): that is a prototype. Then there is an expression w * h, still inside function main which is evaluated but nothing is done with the result.

wallyk
There is. As a subfunction of `main`. Which is not a good idea given that the declaration is at outmost scope.
Benoit
@Benoit: lol you're right I did not see it either :S
Vinzenz
@wallyk is correct - this is not a function definition of any sort. Did everyone spot the semicolon? (Yes, if the semicolon were removed the code would still have similar problems, for the reasons already explained.)
aschepler
+1  A: 

You are declaring a global function fun, and you define it inside main. You should declare it outside, or remove the external declaration

Benoit
+1  A: 

You need to define the function outside the main()

Dadam
+2  A: 

Ack...so many things wrong with that. Should be something like this:

#include <iostream>

using namespace std ;

int fun(int, int);

void main(){
    int width,height,mult;

    cin >> width;
    cin >> height;

    mult = fun(width, height);

    cout << mult << endl; 

}

int fun(int w, int h) {
    return w*h;
}

(Been awhile since I touched C++)

Mark
http://ideone.com/RENLr
Mark
Thanks, It's hard to piece together this kind of thing from the intelligible notes I took in class :\
Anteater7171
Take neater notes ;) Especially when it's code... one typo and it won't compile.
Mark