Jeffery Wang
Jeffery Wang

Reputation: 145

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?

Upvotes: 13

Views: 9842

Answers (2)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

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.

Upvotes: 12

SergeyA
SergeyA

Reputation: 62583

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.

Upvotes: 19

Related Questions