I came across a weird static library which contains a main()
function (C++).
I just wonder what the purpose it is.
How does the main()
execute?
(Dynamic-link libraries and static libraries don't have a main function.) The main function is where your source code begins execution, but before a program enters the main function, all static class members without explicit initializers are set to zero.
Static libraries are just collections of object files that are linked into the program during the linking phase of compilation, and are not relevant during runtime.
A static library is a programming concept in which shared libraries with special functionalities, classes or resources are linked to external applications or components, facilitating the creation of stand-alone and executable files.
Static libraries increase the overall size of the binary, but it means that you don't need to carry along a copy of the library that is being used. As the code is connected at compile time there are not any additional run-time loading costs. The code is simply there.
From the linker perspective, it doesn't matter where the main
function is - it can be in a static library as well as in standalone object file, linker couldn't care less. It produces the executable from object files, no matter where they come from, and in the final executable all the distinction between library/non library symbols is lost.
As for the purposes, i can imagine that some sort of specialized application framework could have main in the library, with you providing callbacks to it in form of defined functions.
I just wonder what the purpose it is.
It's a common technique with unit testing or graphics/game engine frameworks to define the main()
entry point of the executable program, and binding the custom class definitions from certain factory pattern templates.
how does the
main()
execute?
It is the main entry point of any c++ program by definition, so the execution is triggered by the program start up linker script.
Using such stuff means you write your client classes in an executable project, bind them with the framework, and omit to define a main()
function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With