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);
}

Recommended Answers

All 2 Replies

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.