-1

I have main.cpp program which include a header file. The implementation of the functions are in other cpp file.

Finlay Lifny
  • 43
  • 1
  • 6
  • 2
    Please take some time to read [the help pages](http://stackoverflow.com/help), especially the sections named ["What topics can I ask about here?"](http://stackoverflow.com/help/on-topic) and ["What types of questions should I avoid asking?"](http://stackoverflow.com/help/dont-ask). And more importantly, please read [the Stack Overflow question checklist](http://meta.stackexchange.com/questions/156810/stack-overflow-question-checklist). You might also want to learn what a [SSCCE](http://sscce.org/) is. – Some programmer dude Feb 12 '14 at 14:00
  • 1
    Are the variables declared in the `main()` function or before it? It should be before, making them [global variables](http://www.learncpp.com/cpp-tutorial/42-global-variables/). – Proxy Feb 12 '14 at 14:00
  • Also, you wrote `extern [var-type] [var-name]` in the header file or you wrote `[var-type] [var-name]` in the header file? – Proxy Feb 12 '14 at 14:01
  • the variables are declared in main!! – Finlay Lifny Feb 12 '14 at 14:04
  • @FinlayLifny Can you show us the code on how it looks like for both the cpp's and the header file? – John Odom Feb 12 '14 at 14:16

1 Answers1

0

Did you declare the actual storage for the variables in main? In the example below, the external variables are declared in common.h. But the actual storage for this vars in in main.cpp.

==> common.h <==
extern int var1, var2, var3, var4;

==> main.cpp <==
#include <iostream.h>
#include "common.h"
#include "other.h"

int var1, var2, var3, var4 = 4; /* the actual storage */
int main(int argc, char **argv)
{
    std::cout << sumVars() << endl;
}

==> other.h <==
int sumVars();

==> other.cpp <==
#include "common.h"

int sumVars() {
    return var1 + var2 + var3 + var4;
}
Sanjaya R
  • 6,246
  • 2
  • 17
  • 19
  • its similar to my code but i declared those variables in main(); how can i use them in another functions declared in another cpp files without the need to make those variables global as you did? Lifny – Finlay Lifny Feb 13 '14 at 06:19
  • If you declared them inside main, then they are local variables (on the stack) and cannot be directly used by other functions even in the same source file and cannot have external linkage. – Sanjaya R Feb 13 '14 at 14:49