DaniWeb IT Discussion Community

DaniWeb IT Discussion Community (http://www.daniweb.com/forums/index.php)
-   C++ (http://www.daniweb.com/forums/forum8.html)
-   -   How to call in the external function? (http://www.daniweb.com/forums/thread188516.html)

evstevemd Apr 24th, 2009 5:03 pm
How to call in the external function?
 
I have two files and I would like to call addition function from functions.cpp in main.cpp. But I get error:

In function `int main()':
error: `addition' has both `extern' and initializer
error: initializer expression list treated as compound expression
warning: left-hand operand of comma has no effect
error: `addition' cannot be used as a function|
||=== Build finished: 3 errors, 1 warnings ===|


Here are files
main.cpp
#include <iostream>

using namespace std;

int main()
{
    int summation;
    int a, b;
    cout <<"Please Enter the two digits to add"<<endl;
    cin>>a>>b;
    //add external f(x) from function.cpp
    extern int addition(a, b);
    summation = addition(a, b);
    cout<<"The sum is "<<summation;
    return 0;

}

functions.cpp
int addition(int a, int b)
{
    int sum;
    sum = a+b;
    return(sum);
}

tux4life Apr 24th, 2009 5:15 pm
Re: How to call in the external function?
 
Add
extern "C++" int addition(int a, int b);
to main.cpp (outside your main function), delete the instruction
external int addition(a, b);
from inside your main function :) ...

main.cpp
#include <iostream>

using namespace std;

// use the external addition function
extern "C++" int addition(int a, int b);

int main()
{
    int summation;
    int a, b;
    cout <<"Please Enter the two digits to add"<<endl;
    cin>>a>>b;
    summation = addition(a, b);
    cout<<"The sum is "<<summation;
    return 0;

}
Now just compile and link them (main.cpp and functions.cpp) togheter ...

evstevemd Apr 24th, 2009 5:32 pm
Re: How to call in the external function?
 
Great man! I appreciate!


All times are GMT -4. The time now is 6:45 pm.

Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC