2
votes

I'm going to completely reword this question since I'm not quite getting the solutions I was looking for (they're helpful but they weren't saying anything the other questions I referenced didn't say).

Given the following 4 files:

file #1: A.h

class A { void a_func(); };

file #2: A.cpp

#include "A.h"

static int x = 4;

void A::a_func() {
    //implementation.
}

file #3: B.h

#include "A.h"
class B { void b_func(); };

file #4: B.cpp

#include "B.h"

static int x = 3;

void B::b_func() {
    //implementation.
}

Question #1: Since B.h includes A.h, is A.cpp a part of B's compilation unit?

Question #2: Would there be an error since A.cpp and B.cpp both declare the same name of a static variable (x)? I hear that static globals have static linkage which is translation-unit dependent, but since I didn't know about question #1 this didn't help me much.

3

3 Answers

3
votes
  • The translation unit consists of everything that comes out of the preprocessor. In gcc, try g++ -E myfile.cpp to see what that is.

  • Static globals have, well, static linkage, so their name does not spill outside the TU. In each separate TU, the static global (whether of the same name or not) will be a separate object, local to that TU only.

0
votes

answer #1: absolutely not

answer #2: no problem at all. try and you'll see it by yourself

0
votes

A "compilation unit" is an independent hunk of source that can be compiled by itself. Each .cpp file is a compilation unit when combined with the .h files that it includes. So the combination of a.cpp and a.h is one compilation unit, and b.cpp with b.h and a.h is another compilation unit.

Since b.cpp does not include a.cpp, there is no conflict with having a static variable with the same name in each.