954,173 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

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);
}
evstevemd
Senior Poster
3,713 posts since Jun 2007
Reputation Points: 462
Solved Threads: 392
 

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 ...

tux4life
Nearly a Posting Maven
2,350 posts since Feb 2009
Reputation Points: 2,134
Solved Threads: 243
 

Great man! I appreciate!

evstevemd
Senior Poster
3,713 posts since Jun 2007
Reputation Points: 462
Solved Threads: 392
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You