C++ static(wip)

Semih Kekül
1 min readSep 30, 2020

--

static keyword makes the function only accessible in the local translation unit. Lets see with examples in the below code snippets: (I am using the nm tool to list the functions in the object files)

linking1.cpp: I did not add linkerHelper.cpp argument to g++ so it could not link the bar(). Also you can see the bar() function in the linking.o file in the nm analysis.

linking2.cpp: bar() is not used so no error.

linking3–1.cpp: the caller foo() of the bar() is not called but still is in the object file. This is because the possibility of that foo() may be used by another transition unit. If you want to prevent this possibility you should add static front of the function declaration.

linking3–2.cpp: You see here foo() is not used in the local transition unit and could not be used by another transition unit. So no linkage required.

linking3–3.cpp: This one has minimum optimization parameter -O0 so the compiler does not optimize out unused foo().

linking4–1.cpp: This is the best practice; both linking.cpp and linkingHelper.cpp is compiled and no linkage problem.

linking4–2.cpp: As I mentioned above, static functions are local to translation unit so linking.cpp can not use linkingHelper.cpp::bar().

linking4–2.cpp: As I mentioned above, static functions are local to transition unit so linking.cpp can not use linkingHelper.cpp::bar().

--

--