As I understand it (and I may be incorrect), when a program is compiled all of the source files are merged into one massive swath of code.
No. compilation takes place in translation units. A .cpp
file will be compiled at a time. All of it's #include
d headers will be literally copied into the file, but the result will be compiled separately from other .cpp
s in your program. They are all then linked together at the end. This is when all the symbols and names are matched up.
If you declare your variables just like that, at "file scope", they will be visible to the rest of the program (although you need a declaration in the other file to actually use it. This is why the declaration would typically go in a header file). If you want translation unit scope, with no visibility outside and no risk of name clash, declare them inside an unnamed namespace:
// File 1
namespace {
int X = 0;
}
and
// File 1
namespace {
float X = 0.0; // No clash!
}
(Bear in mind that any actual implementation may do things it's own way with regard to compiling and linking, but I think I've described a reasonably typical model that you can pretend is true for thinking about most simple cases.)