I have several independently-written translation units; for the sake of discussion, each of which has a (static or extern'ed) global std::string variable. These strings may have different names, unrelated to the names of the TUs. And I don't guarantee that the compiled TUs ever come in contact until they're linked with the TU having the main()
function (say, main.cpp
). They all include the same header, magic1.h
, which defines a global variable named fun_strings
, whose type we shall choose later.
Now, I want to be able to do the following:
#include <string>
#include "magic1.h"
int main() {
// magic2
for(const std::string& s : fun_strings) {
foo(s);
}
}
The point is that even though main.cpp
_doesn't_include_any_of_the_other_TUs_, they have some static code which causes fun_strings to have copies/references/pointers to all of the TUs' individual strings.
The question is, of course, how to make this happen. I denoted "magic1" and "magic2" the places I might place common code in. And for an example TU with a string, take foo.cpp
with std::string just_a_string("I'm a foo fun string");
somewhere in it.
Notes:
- Solution must be thread-safe, although I'm guessing that should not be an issue.
- This is a somewhat simplified version of what I'm actually trying to do, so apologies for the motivation being a bit obscure.
- Ignore the potential for collisions, in the actual problem I'm having there can't be any.
- I would rather not do anything based on dynamically loading the objects and going through their symbol tables (that's what I might be reduced to doing if I fail with a static approach)