gcc -static 会影响所有提供的库吗?

Does gcc -static affect all provided libraries?

gcc 的选项 -static 是只影响紧随其后的一个库还是影响命令行上提供的所有库?

g++ -static -lutils1 -lutils2

GGC 的 -static linkage option 防止共享库 link老化 。所以 所有 link年龄需要的库必须是静态的。这 linker 必须能够找到一个静态库来解析所有 -lname 选项 被传递,以及 GCC 静默的所有默认库的静态版本 附加到 linkage。

这是 -static 选项的预期用途,尽管可以使其更加灵活。

GCC 的 -static 选项只需让 GCC 将选项 -static|-Bstatic 传递给 linker (ld),在 生成的 ld 命令行中位于所有库之前的位置 link年龄。

linker 的 -static 选项与 GCC 的含义不同。来自 the ld manual:

-Bstatic

-dn

-non_shared

-static

Do not link against shared libraries. This is only meaningful on platforms for which shared libraries are supported. he different variants of this option are for compatibility with various systems. You may use this option multiple times on the command line: it affects library searching for -l options which follow it.

(我的重点)

因此 link 用户的 -static|-Bstatic 选项意味着:不要 link 任何共享库 直到另行通知 。稍后 指向 ld 命令行,您可以使用选项 -Bdynamic 取消 -static|-BStatic 的效果,这 将允许再次 linked 动态库,从那时起,直到另行通知

与 linker 不同,GCC 没有取消其 -static 选项效果的选项。但是,GCC 允许您通过 -Wl,<ld-options> 将任意选项传递给 ld。 因此,您 可以 实际上在稍后的命令行中取消 GCC 的 -static 选项,如下所示:

gcc -static -o prog main.o -lfoo -lbar -Wl,-Bdynamic -lgum ...

这将生成一个 linkage 命令行,其中 -lfoo-lbar 必须解析为 静态库,但 -lgum 和任何后续库都可以解析为 像往常一样共享库或静态库。虽然如果你想 "turn on/turn off" dynamic linkage 在命令行的不同点这样,它会更 自然不使用 GCC 的 -static 选项,而是写等价的:

gcc -o prog main.o -Wl,-Bstatic -lfoo -lbar -Wl,-Bdynamic -lgum ...