'Supersede c++ library printed lines

I have a c++ application, where I link my main.cpp with some pre-built libraries (.a files, I dont know their internal details). The main program looks something like this:

int main() {
    printf("..this is my part of the code.\n");
    // other code here
}

Then when I run my application, it produces the following output, where the first line comes from the linked library:

Welcome to product XYZ, version 1.2
..this is my part of the code.

As an experiment, I added an "exit(0)" as the first line in my main.cpp:

int main() {
    exit(0);
    printf("..this is my part of the code.\n");
    // other code here
}

And I got this as the output:

Welcome to product XYZ, version 1.2

My question is, how does the linked library start printing even before the first line of my code gets executed? What would be the code in the library (an example), which would make that behavior? And secondly, if I want my line to be printed before the library line, how would I go about doing it?

(Note: the subject line for this question may not match the exact question that I am asking, I was not sure how to frame the subject line to summarize my question. Apologies for that in advance.)

c++


Solution 1:[1]

As everyone has said in the comments, initializer code for statics and globals is executed before main(), and if this code prints a message, you cannot have something in main() supersede it. Suppose your main program is in main.cc, as you have it, and the library has a single file, thing.cc, like this:

#include <iostream>
class Thing {
public:
  Thing() { std::cout << "Welcome to the Thing." << std::endl; }
};
static Thing _thing;

Now, compile this way:

c++ thing.cc -o thing.o
c++ main.cc thing.o -o main
./main

and you'll see the message from Thing appear before you can even exit.

When there is more than one, the order of these initializers is implementation-dependent, but they are all guaranteed to happen before main() is called.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Derek T. Jones