On 4 December 2011 17:40, Tom Gall tom.gall@linaro.org wrote:
I probably know the answer to this already but ...
For shared libs one can define and use something like:
void __attribute__ ((constructor)) my_init(void); void __attribute__ ((destructor)) my_fini(void);
Which of course allows your lib to run code just after the library is loaded and just before the library is going to be unloaded. This helps keep out cruft such as the following out of your design:
PleaseCallThisLibraryFunctionFirstOrThereWillBeAnErrorWhichYouWillHitCausingYouToPostToTheMailingListAskingTheSameQuestionThatHasBeenAsked1000sOfTimes();
Yeah .. you know the function. I don't like it either.
Unfortunately this doesn't work when people link in the .a from your lib. Libs like libjpeg-turbo in theory should never ever need to be linked in that fashion but consider the browsers who link to the universe instead of using system shared libs.
If we accept that linking .a's valid use, and we don't want to promote the use of the function that won't be named in the design and use of libraries, then I'd like to think for the good of humanity the toolchain should allow for the use of __attribute__ ((constructor)) and __attribute__ ((destructor)) to continue to work in the static link case.
Maybe this has already been solved, in which case where is that fine manual as I clearly have some reading to do!
There is no standard way to do this in C. The constructor/destructor attributes you mention are of course gcc extensions, and as you say, they only work for shared libraries.
The usual way to solve this is to do any static initialisation required as part of some other function all users would have to call anyway. For libjpeg, the jpeg_create_(de)comress() functions would be the right place.