Every translation unit must contain a declaration of every symbol it uses. On the other hand, every symbol must have a definition in exactly one translation unit (unless it's explicitly or implicitly inline
; then multiple translation units can have definitions as long as they're all the same).
The usual way to do this is to put the declarations for things in a header file, which you then #include
into multiple translation units, while putting their definitions in a .cpp file that forms the main body of the translation unit.
In this particular case, you need a declaration of var
in the translation unit that contains main
. You could put it in a header that gets #include
d into file1.cpp; i.e.:
file2.hpp:
#ifndef FILE1_HPP
#define FILE1_HPP
extern int var;
#endif
file2.cpp:
#include "file2.hpp"
int var;
file1.cpp:
#include "file2.hpp"
#include <iostream>
int main() {
std::cout << var;
}
Or you just put it into that translation unit manually; i.e.
#include <iostream>
extern int var;
int main()
{
std::cout << var;
}
Either approach is exactly the same from the compiler's point of view (the preprocessor just does text replacement), but the latter tends to be much more difficult for humans to deal with, so you should probably avoid it in general.