You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何Linux平台GCC编译带覆盖率选项的共享库时未出现`__gcov_xxx`未定义引用,而Windows(Cygwin)平台却出现该问题?

Why does GCC on Cygwin throw undefined references to __gcov_xxx when compiling with --coverage, but Linux GCC doesn't?

Great question—this boils down to platform-specific differences in how GCC handles coverage instrumentation linking between Linux and Cygwin. Let’s break it down step by step:

1. Linux GCC’s Automatic Linking Behavior

When you use --coverage with GCC on Linux (like your Ubuntu 11.4.0 example), the compiler and linker work behind the scenes to pull in the necessary GCov support libraries automatically.

  • During compilation, --coverage adds instrumentation code that references __gcov_init, __gcov_exit, and __gcov_merge_add.
  • During linking (even for shared libraries), Linux GCC implicitly links against libgcov.so (the shared GCov runtime library). This resolves all those __gcov_xxx symbols without you needing to explicitly specify -lgcov or repeat --coverage in the link step.

You can confirm this by running ldd ./a.out (or your shared library) on Linux—you’ll see libgcov.so listed as a dependency.

2. Cygwin GCC’s Explicit Linking Requirement

On Cygwin, the GCC toolchain doesn’t automatically link the GCov runtime when building shared libraries, even if you used --coverage during compilation.

  • The compilation step still adds coverage instrumentation (hence the undefined references show up), but the linker doesn’t include the GCov library unless you explicitly tell it to.
  • This is likely due to Cygwin’s POSIX compatibility layer implementation—linker behavior here is stricter about explicit library dependencies compared to Linux.

Fix for Cygwin

To resolve the undefined references, you need to add --coverage (or -lgcov) to the link step as well:

echo 'void f(void){}' | gcc -xc - --coverage -fPIC -c -o x.o && gcc --coverage -shared x.o

By repeating --coverage during linking, you instruct the linker to include the GCov runtime library (libgcov.a or libgcov.dll on Cygwin), which provides the missing __gcov_xxx symbols.

Quick Recap

  • Linux: --coverage in compilation triggers automatic linking of the GCov runtime for shared libraries.
  • Cygwin: You must explicitly specify --coverage (or -lgcov) in the link step to resolve GCov symbols.

内容的提问来源于stack exchange,提问作者pmor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 12:22:30