File static and unnamed namespace

Hi all,

Kindly explain these two terms, I do not want the difference between them, just explanation of them.
Thanks ..
i understood what is file static : global static variables , but still not clear with unnamed namespaces
Also what is the meaning of the term "translation unit"?
if you put a variable inside an unnamed namespace it is a global variable without linkage. So the linker has no idea that this variable exists.

if you include such a variable in different compiler units (*.cpp) you will have muliple instance of a variable with the same name.

I.e.

x.h
1
2
3
4
namespace
{
int x;
}

a.cpp
1
2
3
4
5
6
7
8
9
10
11
#include "x.h"

void a_changeX()
{
  x = 101;
}

void a_printX()
{
  std::cout << "x = " << x;
}

b.cpp
1
2
3
4
5
6
7
8
9
10
11
12
#include "x.h"

void b_changeX()
{
  x = 202;
}


void b_printX()
{
  std::cout << "x = " << x;
}


main.cpp
1
2
3
4
5
6
7
8
9
10
int main()
{
  a_changeX();
  b_changeX();

  a_printX();
  b_printX();
  return 0;
}
x = 101
x = 202
Last edited on
From the above code, the compiler will generate 3 object files:
a.cpp -> a.o
b.cpp -> b.o
main.cpp -> main.o

The linker will create the executable from the object files.

Now, the main.cpp probably includes a.h and b.h (to know about those functions). Preprocessor essentially concatenates the headers with main.cpp. Compiler takes the result and computes the object file. This is one translation unit.

a.cpp with x.h, iostream, and a.h is another unit.
b.cpp with x.h, iostream, and b.h is another unit.

Translation units are independent of each other; you could compile them simultaneously, in parallel.
Translation units may (re)use same code (like the x.h and <iostream>).
Oh!!. i was thinking translation unit means one function in a program , certainly i was wrong :)
Last edited on
And why unnamed namespace is superior to file static?
The whole (small) program can be in one translation unit.
http://stackoverflow.com/questions/1106149/what-is-a-translation-unit-in-c
Topic archived. No new replies allowed.