[SOLVED] Is a translation unit valid C++? And is a translation unit (for GCC) the output of g++ -E?


This Content is from Stack Overflow. Question asked by Enlico

I was convinced that a translation unit is a .cpp file (or, to avoid referring to an extension, a file you would feed to `g++ -c theTranslationUnit.cpp -o whatever.o) once you substitute into it the macros and copy and paste the #includes (recursively).

In other words, I was thinking of it as “take a C++ file and process all the #s and delete all the comments in it”.

However, I’ve recently found this very clear answer about what are the step that GCC performs, and I experimented with those info, finding out that the typical output of g++ -E someSource.cpp looks like this

# 0 "main.cpp"
# 0 "<built-in>"
# 0 "<command-line>"
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 0 "<command-line>" 2
# 1 "main.cpp"
# 1 "Foo.hpp" 1
struct Foo {
# 2 "main.cpp" 2
int main() {

which I can farily easly understand what it is, but…

  • is it valid C++ code? Clearly I can feed it to g++, but that’s, I believe, just because it can recognize it and process is accordingly, e.g. skipping the preprocessing step.
  • Is it the thing known as translation unit? As in, with all those #-lines?


is it valid C++ code?

It’s not a "strictly conforming" C++ code.

There is only that many # https://eel.is/c++draft/gram.cpp preprocessor directives. # <number> "source" <number> falls into # conditionally-supported-directive case, in which case https://eel.is/c++draft/cpp.pre#2 :

A conditionally-supported-directive is conditionally-supported with implementation-defined semantics.

It happens to be conforming C++ code that may be accepted by a conforming C++ compiler that supports this semantic.

Is it the thing known as translation unit? As in, with all those #-lines?

Yes, it is a translation unit. It’s a segment of text that is an input to the compiler (translator).

It’s really not relevant. C++ places no requirements on the output of gcc -E, gcc can do what he wants here and output what he wants. It’s not relevant from C++ standard point of view nor from gcc point of view, if this is valid C++ code or not. This is internal gcc output for gcc use. You may be interested in How to remove lines added by default by the C preprocessor to the top of the output? .

This Question was asked in StackOverflow by Enlico and Answered by KamilCuk It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?