P. Danielski
P. Danielski

Reputation: 560

C++ About variables

I'm reading a c++ book(c++ primer) and now there is a thing I can't figure out.
Why if I have 2 different cpp files and I declare&define a variable with the same name in these files, the compiler give me an error of linkage? Are the variables local to file?

Upvotes: 1

Views: 73

Answers (2)

Innot Kauker
Innot Kauker

Reputation: 1373

If you declare the variables with the static keyword, they will be local to corresponding compilation units and you won't receive an error. Otherwise they are global and should be accessible for the entire program, hence the error you get.

Upvotes: 1

H Walters
H Walters

Reputation: 2674

Are the variables local to file? No.

There's nothing particularly special about a cpp file as opposed to a h file; when you compile a cpp file (say, in the standard manner, to a .o), the #include that pulls in the h file is simply injecting the h file into the compilation stream. Header files in this regard are organizational entities.

You can put int foo; in one cpp file, and extern int foo; in another, compile each to an object file and link them together. The second file can then access the same object in the first file (the fact that extern int foo; was shoved into the cpp file is really not relevant). For the same reason, int foo; placed into two different cpp files creates an ambiguity when linking them together.

To make sure the int foo in one translation unit (compiled .o/.obj file if you will) is really only used by that unit, you can do one of two things:

  1. Declare the foo object static, like this: static int foo; This variable is immune to external linkage; it's truly private to one translation unit.
  2. Put the int object in an unnamed namespace, like this:

    namespace { // Foo is in a unique namespace for this object file int foo; }

This special construct generates a unique namespace for each translation unit. This causes each foo object across object files to be distinct.

Upvotes: 1

Related Questions