We have 2 cases (scenarios). In each case, we have 2 files : main.cpp
and file.cpp
Case 1
#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
#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 :
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.