Is is possible to register a function to be run immediately before main
is entered? I know that all global objects are created before entering main
, so I could put the code in the constructor of a global object, but that does not guarantee any particular order. What I would like to do is put some registration code into the constructor, but alas, I don't know what to put there :) I guess this is highly system-specific?
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Keeping track of variable instances
- Why does const allow implicit conversion of refere
- thread_local variables initialization
相关文章
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
- What is the correct way to declare and use a FILE
If you're using
gcc
, you can use theconstructor
attribute on a function to have it called beforemain
(see the documentation for more details).Goal
Let's say you want the following:
Implementation
C++ version - static variable + constructor:
C version - static variable + function
Notes
IMHO, the C++ version is slightly more elegant. In-theory, it consumes slightly less space. Otherwise, potato, po-tat-oh.
Caveat: I haven't tested the "C" version on a proper C-only compiler. Fingers crossed; post a note if it doesn't work.
Caveat: Compiler portability in general is a tricky thing. I wouldn't be shocked if there's a bug on some other compiler.
The BOOST_PP_CAT code is stolen from boost/preprocessor/cat.hpp. I simplified the implementation, and in the process may have compromised portability. If it doesn't work, try the original (more verbose) implementation, and post a comment below. Or, if you are already using Boost, you can just use their version.
If you are trying to understand the Boost magic, note that (at least for me, and in this scenario), the following also seems to work:
Not sure this is exactly what you want... But it should do the job.
It's better to explicitly calls such registration functions, either in main or on first access (but first access init could pose issues if you're multithreaded).
I am guessing here but:
C++ defines that a function-static is initialized sometime before it is first accessed, so you can work around it in the way shown below.