1

I have seen the definition of a namespace is split across multiple header files, and the header files are included in one file. For example, How to use namespace across several files

Can the definition of a namespace span multiple translation units?

I am comparing namespaces in C++ to packages in Java. A package in Java can span multiple translation units.

svick
  • 236,525
  • 50
  • 385
  • 514
  • 2
    Yes of course. You routinely include various combinations of standard headers into various source files; those headers all contain different pieces of namespace `std` – Igor Tandetnik Oct 07 '17 at 00:26
  • Do those header files belong to the same translation unit? –  Oct 07 '17 at 00:27
  • Of course they do. `` defines `std::istream`, `std::ostream`, and others. `` defines `std::find()`, `std::transform()`, and others. Etc... – Sam Varshavchik Oct 07 '17 at 00:28
  • 2
    Actually, you're better off ***NOT*** comparing Java to C++. Despite the very similar syntax and grammar, the fundamental principles and concepts of C++ are completely different from the vaguely similar principles and concepts in Java. If you try to draw analogies between C++ and Java you are almost guaranteed to keep going down one rabbit hole after another. The flaming wreckage of everyone who preceded you, down this path, can be found all over stackoverflow.com. You'll be better off forgetting everything you know about Java, and focus on learning C++ from the ground up, using a good book. – Sam Varshavchik Oct 07 '17 at 00:29
  • By definition, a translation unit is a source file together with all the files included into it; roughly, a single source file after it passed preprocesssor. In light of this, your question doesn't quite make sense. – Igor Tandetnik Oct 07 '17 at 00:32
  • @SamVarshavchik Thanks. What good book do you recommend for C++? I have The C++ Programming Language, but I like OReilly's in a nutshell more, and C++ in a Nutshell is outdated. –  Oct 07 '17 at 02:01

1 Answers1

3

Namespace doesn't have declaration and definition. Declarations and definitions are in the namespaces.

Translation unit is everything you get after being preprocessed. In particular, preprocessor includes header files to the source files.

Imagine you have one header and two source files with namespaces. After preprocessing you get namespace from header spans two source files. And it will be compiled.

So you can split namespace between source files.

header.h

namespace ns {

void f1();
void f2();

}

source1.cpp

#include "header.h"

namespace ns {

void f1() {

}

}

source2.cpp

#include "header.h"

namespace ns {

void f2() {

}

}

And stop compare C++ and Java. They have different fundamental concepts.

boriaz50
  • 860
  • 4
  • 17