0

Can please someone explain me how to link the functions @ functions.cpp to main.cpp

note: I want both files functions.cpp and main.cpp to use the same variables from header.h

Thank you!

main.cpp

#include "Header.h"
#include <iostream>

using namespace std;
int multi();
int printOutRanomdNumber();    


int main()
{
cout << "Eneter a number you want to multiply" << endl;
cout << multi() <<endl;
cout << printOutRanomdNumber();

system("pause");
return 0;
}

header.h

#ifndef _HEADER_
#define _HEADER_

#include <iostream>

using namespace std;

extern int randomNumber;
int multi();
int printOutRanomdNumber();    


#endif

functions.cpp

#include "Header.h"
#include <iostream>

using namespace std;

int multi()
{
    int x;
    cin >> x;
    return(x=x*x);
} 
int printOutRanomdNumber()
{
    cout << "Please enter a random number" << endl;
    cin >> randomNumber;
    return (randomNumber);
}
loganfsmyth
  • 156,129
  • 30
  • 331
  • 251
alentor
  • 27
  • 3
  • 12

1 Answers1

1

The error is because you've not defined int randomNumber in any of your files.

You need to define randomNumber in one of the .cpp files, I'm guessing functions.cpp makes more sense here.

Also you can get rid of these lines in main.cpp since you're including Header.h which provides the prototypes already.

int multi();
int printOutRanomdNumber();
Tuxdude
  • 47,485
  • 15
  • 109
  • 110
  • The purpose of `extern` is to allow a single object to be shared across multiple TU's. What you suggest is detrimental to this purpose. How do other TU's know of the `extern` if the declaration is removed from header? One might argue that the object is only needed in `functions.cpp` but in that case why make it `extern` to begin with? What you suggest will solve the compilation and linking errors in this case but it is not the right way to solve these problems. – Alok Save Mar 05 '13 at 04:40
  • Thank you it did solve the problem! is there a way to define a variable in .h file and use it in two of the .cpps? – alentor Mar 05 '13 at 04:41
  • 1
    Actually yes, I didn't realize you could define the extern keyword and also have the definition of the variable in the same scope. So yes, you could leave the definition in the header, let me update the answer. – Tuxdude Mar 05 '13 at 04:46