diff --git a/_posts/2016-11-11-globals.md b/_posts/2016-11-11-globals.md index 74f58df110d..a8ec8f8d514 100644 --- a/_posts/2016-11-11-globals.md +++ b/_posts/2016-11-11-globals.md @@ -6,11 +6,10 @@ author: Nir Friedman and Sandeep Kumar Gupta Doing a global correctly in C++ is not a trivial thing, when the global itself is non-trivial. Or, put another way: globals that have constructors and -destructors can easily make a big mess. There's surprisingly few resources +destructors can easily make a big mess. There are surprisingly few resources summarizing exactly what considerations are relevant in order to make sure -globals behave themselves. There are some well known cases, like static -initialization order fiasco (SIOF). Maybe this is because to really talk about -globals, we have to talk about the linker, and the linker is a strange beast. +globals behave themselves. There are some well known cases, like [static initialization order fiasco][siof] +. Maybe this is because to really talk about globals, we have to talk about the linker, and the linker is a strange beast. Without it, you can't write any real C++ program, but it's not covered by the standard, its behavior is relatively rarely discussed, and varies from platform to platform. @@ -72,6 +71,9 @@ There are three translation units (TUs) here, one for each file ending in `.cpp`. As far as a compiler is concerned, all of these translation units are kosher. Let's try to link this together and see what happens: +==> Not sure how this looks in final page, but they look pretty bad in markdown page in browser. How about making +==> this as they appear in terminal? + {% highlight bash linenos %} # Compile static translation unit clang++ -std=c++14 -c -fpic static.cpp @@ -275,3 +277,12 @@ Key point: assembly analysis shows that with static linked first, executable initializes global, otherwise it doesn't. Shared library will initialize it either way. Because the symbol of the global itself is already defined before either initialization occurs, the initialization occurs on the same symbol. + +[[siof]]: https://isocpp.org/wiki/faq/ctors#static-init-order + + +[Comment to be removed] +* I found this article http://www.lurklurk.org/linkers/linkers.html while searching for whether c++ standard talks about linking or not. Not sure how useful it is. +* Do you think it makes sense to run main.x.cpp under address sanitizer to see how it performs? +* The other thing that I noticed is usage of both "we need to understand" and "you need to understand". The latter seems pedantic, so prefer first? +* To see all the symbols in an executable I find this command handy: `readelf -s main.x.o | c++filt`. It lists undefined symbols as UND