Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does static library contain a main function?

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?

like image 409
Jeffery Wang Avatar asked Nov 09 '16 19:11

Jeffery Wang


People also ask

Do libraries contain a main function?

(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.

What does static library contain?

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.

What is the point of static libraries?

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.

What are the advantages of static library over shared library?

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.


2 Answers

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.

like image 159
SergeyA Avatar answered Nov 03 '22 02:11

SergeyA


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.

like image 39
πάντα ῥεῖ Avatar answered Nov 03 '22 00:11

πάντα ῥεῖ