MWE
#include <iostream>
struct Foo {
Foo() {
std::cout << "Constructing Foo " << this << std::endl;
}
~Foo() {
std::cout << "Destructing Foo " << this << std::endl;
}
};
Foo global_foo;
int main () {
std::cout << "Entering and exiting main()" << std::endl;
return 0;
}
The problem
Compile the above with options -fprofile-arcs -ftest-coverage
, runn the program, and then run gcov. The program output clearly shows that Foo::Foo(), main(), and Foo::~Foo() are called, in that order. The gcov output shows that Foo::Foo() and main() are called, but not Foo::~Foo().
Root cause
The global objects are destroyed by a GNU internal exit handler (function registered with at_exit()). The final gcov stats are produced by another exit handler. The gcov exit handler is obviously called before the global destruction exit handler, so gcov doesn't see the destructors being called.
Bug status
This is an old, old bug in gcov. Here's the Bugzilla link: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=7970. The bug still exists nine years later, at least in i686-apple-darwin10-g++-4.2.1.
The question
Is this an unresolvable bug in gcov, something I have to live with, or is it just something that happened to slip through the cracks (nine years old and utterly forgotten)? If the latter, how to fix it?
First off, note that that bug report hasn't been reconfirmed since 2005; you should probably add a note saying that you're still seeing the bad behavior in g++-4.2.1. Even if no one acts on your message, it's useful to have that information out there.
Short term, if you want to go on using gcov you have to live with it. You might consider lcov instead, which gives you the ability to exclude specified lines from the coverage analysis. Fair warning: I've heard that it's nice, but I've never used it myself.
Medium term, add that response to the bug tracker! No guarantees, but perhaps that will generate enough interest for some kind soul to write you a patch.
Long term, if no one is willing to patch it for you, you may be able to patch it yourself. gcc is not the friendliest codebase in the world, and getting your changes accepted can be an adventure, but if you really need this, you can make it happen.
Best of luck.
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