使用任意库文件制作 gcc -x somelang link 而无需 -L'ing 其目录?

Make gcc -x somelang link with an arbitrary library file without -L'ing its directory?

我有一个名为 foo.bar 的源文件,出于这个问题的目的,不能重命名或 linked 到。假设它是一个 C++ 源文件。现在,我想编译它并 link 它,在同一个命令中,使用 path/to/weird_lib_file 处的库。现在,如果源文件名是 foo.cpp,我可以这样做:

gcc -o foo foo.cpp /path/to/weird_lib_file

那行得通。但是如果我写

gcc -o foo -x c++ foo.cpp /path/to/weird_lib_file

没用。现在,我可以做到

gcc -o foo -x c++ foo.cpp -L /path/to/ -l:weird_lib_file

此处建议:

How to link using GCC without -l nor hardcoding path for a library that does not follow the libNAME.so naming convention?

但出于某种我也不会深入探讨的原因,我宁愿不 -L 那个文件夹。我还能以某种方式强制 GCC link 针对那个单独的库文件吗?好像-l:/path/to/weird_lib_file不行。

如果您没有 -L 库的路径,您可能 通过绝对或相对路径名指定库。在里面 后一种情况,无论调用什么库,都将采用 作为 linker 输入,除非它有扩展名 似乎是一个源文件。于是

gcc -o prog main.c foo.xyz

将使用库 ./foo.xyz 编译 main.c 和 link main.o 如果 事实上,无论是静态的还是共享的,都可以满足 linkage.

以后

(编辑前,问题没有提到-x选项)。

-x 选项的引入如:

gcc -o prog -x c++ main.cpp foo.xyz

引发如下错误:

foo.xyz:2:1: error: stray ‘`’ in program
 /               0           0     0     0       16        `
 ^
foo.xyz:3:1: warning: null character(s) ignored
       T_Z3foov foo.o/          0           0     0     644     1544      `
 ^
foo.xyz:3:4: error: stray ‘’ in program
       T_Z3foov foo.o/          0           0     0     644     1544      `
    ^
...
...

即使 foo.xyz 实际上是一个可以满足 link 年龄的图书馆, 用一个非正统的名字。

因为它必须,因为 -x c++ 指示 gcc 解释后续输入文件 作为 C++ 源代码,直至另行通知。作为 documented

-x language

Specify explicitly the language for the following input files (rather than letting the compiler choose a default based on the file name suffix). This option applies to all following input files until the next -x option.

并且永远不会有进一步的通知。

当然,这种情况不会发生,例如的:

gcc -o prog -x c++ main.cpp -L. -l:foo.xyz

因为 -l:foo.xyz 不是输入文件而是 linker 选项(其中,在 与 -L. 一起指定一个输入文件)。

为了避免这种结果,你必须放弃 foo.xyz 是 通过在到达之前取消 -x c++ 来生成 C++ 源文件,例如:

gcc -o prog -x c++ main.cpp -x none foo.xyz

如文件所示:

-x none

Turn off any specification of a language, so that subsequent files are handled according to their file name suffixes (as they are if -x has not been used at all).