Mouin Mouin - 2 months ago 10
C Question

Two main functions in a C application

I'm actually put in a big project. My first step to understand the code was to search the

main
function so that I have a vision of the architecture.

What I discovered is that there is more than one main function. It's true that they are in different folders, but I don't understand how this application succeed to build. What I know is that the linker expects one
main
function (Entry point).

I believe it's too hard to understand the build process of the application, so I'm asking because for sure some of you have encountered this.

1 - Should I have theoretical background to understand this? If so, please suggest me articles, books, what ever you want.

2 - When do we have to use several
main
functions in one application?

Answer

You can't have multiple main functions for a single executable. There are several possibilities.

If doing a build builds only a single application, then only one of the main functions will be compiled. (Or none, if there's an option to build a library rather than an executable.) There are probably options that determine which one to build, depending on which variant of the application you want, the target system, or something else.

Or perhaps the application consists of multiple executables, with one main function for each one.

If running the build doesn't take too long, a trick I've used to determine which of several source files is actually compiled is to temporarily add #error directives, like:

#error "TEMPORARY: This is /full/path/to/source.cpp"

The resulting error message will tell you which source file was actually compiled. (You can also use #warning directives if your compiler supports them.)

Comments