-1

We have 2 cases (scenarios). In each case, we have 2 files : main.cpp and file.cpp

Case 1

  • main.cpp :
#include <iostream>

#include "file.cpp"  // this line is what matters

int main () {...}

I compile and run by doing:

g++ main.cpp -o main && ./main

Case 2

  • main.cpp :
#include <iostream>

void filefunc(int); // function declaration from file.cpp

int main () {...}

I compile and run by doing:

g++ -c main.cpp
g++ -c file.cpp
g++ main.o file.o -o main && ./main

How many translation units do we have in each case ? is it :

  • one for the first
  • two for the second
Mohamed Benkedadra
  • 1,964
  • 3
  • 21
  • 48

1 Answers1

2

Every time you pass a file of source code to g++, that is a translation unit. By definition.

The file extension is practically irrelevant, but conventionally we reserve ".cpp" for things that we pass to the compiler, not things we #include.

In the first case, your ill-advised inclusion of a .cpp file results in a single translation unit that would confuse your fellow programmers and cause rejection at code review.

In the second case, you have two translation units.

This time, the end result — the executable — is the same though.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055