KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
Is there any way to make a function get called just by linking its .o file? For example: foo.cpp: extern int x; void f() { x = 42; } struct T { T() { f(); } } t; // we use constructor of global // object to call f during initialization bar.cpp: #include <iostream> int x; int main() { std::cout << x; } To compile/link/run: $ g++ -c foo.cpp $ g++ -c bar.cpp $ g++ foo.o bar.o $ ./a.out 42 This seems to work with gcc 4.7. It outputs 42 as expected. However I remember on some old compilers I had a problem with this pattern that because nothing was really "using" foo.o it was optimized out at link time. (perhaps this particular example is not representative of the problem for some reason) What does the C++11 standard have to say about this pattern? Is it guaranteed to work?
Tags (comma-separated)
Save Edits
Cancel