If you want both to refer to the same variable, one of them must have int k; , and the other should have extern int k;
In this situation, you usually put the definition ( int k; ) in a single .cpp file and put the declaration ( extern int k; ) in the header, which should be included wherever you need access to this variable.
If you want each k be a separate variable that has the same name, you can mark it as static , for example: static int k; (in all files, or at least all but one file). Alternatively, you can anonymous namespace:
namespace { int k; };
Again, in all, but not more than one of the files.
In C, the compiler is usually not so picky. In particular, C has the concept of "preliminary definition", so if you have something like int k; twice (in the same or separate source file), each will be considered a preliminary definition, and there will be no conflict between them. This can be a bit confusing, however, since you still don't have two definitions that include initializers - a definition with an initializer is always a complete definition, not a preliminary definition. In other words, int k = 1; appearing twice will be an error, but int k; in one place and int k = 1; otherwise it will not. In this case, int k; will be considered as a preliminary definition and int k = 1; as a definition (and both refer to the same variable).
Jerry Coffin Apr 6 2018-12-12T00: 00Z
source share